数据结构学习--创建链表
#include "stdio.h" #include "stdlib.h" struct pass { int number; struct pass *next; }; struct pass * createList(struct pass *head) { int i = 0; struct pass *p1; /*要新加的节点*/ struct pass *p2; /*尾节点*/ head = NULL; /*头节点*/ p1 = (struct pass*)malloc(sizeof(struct pass)); p2 = p1; p1->next = NULL; for(i = 1; i<=10; ++i) { if(p1 == NULL) return; p1->number = i; if(head == NULL) { head = p1; //第一次循环时, 表是空的, 将p1设置为表头,此时head == p2 == p1; } else { p2->next = p1; //第二次开始, p1是新的节点, p2是表尾, 将表尾的next指向新节点 } p2 = p1; //p2设为表尾 p1 = (struct pass*)malloc(sizeof(struct pass)); } p2->next = NULL; //没有这一句, p2将指向不明位置,导致下面的temp ==NULL的判断不起作用 free(p1); //一定要将将p1 free并且置为NULL, 否则指针变成"野指针", "野指针"指程序不再使用的指针, //程序员无法控制,free只是把指针所指的内存释放掉, 并没有删除指针. p1 = NULL; return head; } void print(struct pass *head) { struct pass *temp; temp = head; while(temp != NULL) { printf("%d ", temp->number);//如果没有p2->next = NULL, 将导致错误. temp = temp->next; } } int main() { struct pass *head = NULL; head = createList(head); print(head); }
结果如图: