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