1,单向链简洁。
单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始;链表是使用指针进行构造的列表;又称为结点列表,因为链表是由一个个结点组装起来的;其中每个结点都有指针成员变量指列表中的下一个结点;列表是由结点构成,由head指针指向第一个成为表头的结点而终止于最后一个指向nuLL的指针;
2,例子要求:
根据示例代码中的例子,完成单向链表(single linked list)中的以字符串为数据的链表的插入、删除以及查找,并支持单向链表的反转;
3,代码实现。
#include <stdio.h>#include <math.h>#include <cstring>#include <memory.h>#include <malloc.h>//节点的定义typedef struct Node { void *data; //数据域 //链域 struct Node *next;} NodeStruct, *pNode;pNode head = NULL; typedef char (*pCompareFunc)(void *a, void *b);typedef void* (*pChar)(void *p);// 字符串判断int str_compare(void *a, void *b) { char *pa = (char*)a; char *pb = (char*)b; return strcmp(pa , pb);}// 分配一个节点pNode allocate_node(void *data, pChar char_func) { pNode node = allocate(); node->data = char_func(data); return node;}// 创建节点pNode allocate() { void *p = malloc(sizeof(NodeStruct)); pNode node = (pNode)p; node->next = NULL; node->data = NULL; return node;}// 添加一个节点void insertNode(pNode node){ if (head == null){ head=node; } else { node->next = head; head = node; }}void* char_char(void *p) { char* pa = (char*)malloc(sizeof(char)); memcpy(pa, p, sizeof(char)); return pa;}// 初始化节点pNode allocate_node(void *data, pChar char_func) { pNode node = allocate(); node->data = char_func(data); return node;} // 释放资源void free_list(pNode node) { pNode next = node; while (next != NULL) { if (next->data != NULL) free(next->data); pNode temp = next; next = next->next; free(temp); }}// 1.1 添加一个节点void insert(pNode node) { if (head == NULL) head = node; else { node->next = head; head = node; }}//1.2查找int str_search(void* data,pCompareFunc compare){ pNode next = head; pNode prev = NULL; while (next != NULL ) { if (compare(data, next->data) == 0) { // 如果查找到了,就退出返回1 return 1; break; } prev = next; next = next->next; } // 如果一直查找不到,就返回0 return 0;}// 1.3删除节点void remove(void* data,pCompareFunc compare) { pNode next = head; pNode prev = NULL; while (next != NULL) { if (compare(data, next->data) == 0) { if (prev == NULL) { head = next->next; next->next = NULL; free_list(next); } else { prev->next = next->next; next->next = NULL; free_list(next); } break; } prev = next; next = next->next; }}//1.4反转void invert_order(){ node *This,*prev; p=head.next; This=NULL; while(p) { prev=This; This=p; p=p->next; This->next=prev; } head.next=This;} void main(){ // 1单向链表 char a1[] = 'aaa1'; char a2[] = 'aaa2'; char a3[] = 'aaa3'; // 1.1添加 insertNode(allocate_node(a1, init_char)); insertNode(allocate_node(a2, init_char)); insertNode(allocate_node(a3, init_char)); // 1.2查找 int flag = 0; flag = str_search(&a2,str_compare); // 1.3删除 remove(&a2,str_compare); // 1.4反转 invert_order();}
以上就是对 C语言单向联表的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!
新闻热点
疑难解答
图片精选