搬运自我的CSDN https://blog.csdn.net/u013213111/article/details/88382961
!!!Attention:以下操作中的单链表均带有头结点!!!
1.定义
定义一个eletype,便于更改元素的类型。node结构体有两个成员,一个是数据成员,一个是指向下一个节点的指针成员。给node结构体起个别名Lnode,这样就可以直接定义Lnode型变量,无需用struct node这么长的名字。
1 typedef int eletype; 2 3 typedef struct node 4 { 5 eletype data; 6 struct node *next; 7 }Lnode;
2.创建一个有n个元素的单链表
函数的返回值应该是表头(指针),这样才能够使用所创建的单链表。所以肯定要先创建Lnode *head。创建新的元素要用到malloc函数分配内存。
1 Lnode *CreateList(int n) //Create a single linkedlist with n elements 2 { 3 Lnode *head, *current, *s; 4 head = (Lnode*)malloc(sizeof(Lnode)); 5 current = head; 6 for (int i = 0; i < n; i++) { 7 s = (Lnode*)malloc(sizeof(Lnode)); 8 s->data = 100 - i; 9 current->next = s; 10 current = s; 11 } 12 current->next = NULL; 13 return head; 14 }
3.删除单链表
删除一个元素前首先把它所指向的下一个元素保存到tmp,然后free当前元素的空间,再移到下一个元素去,重复上述步骤。如果表头没有被free的话用valgrind是会检测到内存泄漏的,其实就只是清空了表,而不是真正的删除整个表。
1 void DeleteList(Lnode *head) //Delete list 2 { 3 Lnode *current, *tmp; 4 current = head->next; 5 head->next = NULL; 6 while (current != NULL) { 7 tmp = current->next; 8 free(current); 9 current = tmp; 10 } 11 //If just want to clear the list, do not free(head) 12 free(head); //Forget to free head can lead to memory leakage. 13 }
4.打印单链表
注意遍历之前首先要检测一下是否是空表,然后逐个元素进行打印就好。
1 void PrintList(Lnode *head) //Print list form head to end 2 { 3 Lnode *current; 4 if (head->next == NULL) 5 printf("The list is empty.\n"); 6 else { 7 current = head->next; 8 while (current != NULL) { 9 printf("%d\n", current->data); 10 current = current->next; 11 } 12 } 13 }
来源:https://www.cnblogs.com/lyrich/p/10552139.html