这两天搞了搞链表,发现这东西挺好用的,特此记录一下自己敲下的代码,希望给后面的人一点启发 = =
代码可以直接拷贝测试
下面是链表节点,这里用来测试,就没搞很多字段了
1 typedef struct Student_Node{ 2 int id; 3 struct Student_Node *next; 4 }Student_Node; 5 6 typedef Student_Node *Student;
接下来是节点的创建函数
1 Student creatStudent(int n) 2 { 3 int var; 4 Student s,p,index; 5 s = malloc(sizeof(Student));//头结点 6 s->id = n; 7 index = s; 8 for (var = 1; var <= n; ++var) { 9 p = malloc(sizeof(Student)); 10 p->id = var; 11 index->next = p; 12 index = p; 13 } 14 index->next = NULL; 15 return s; 16 }
添加节点函数,这里用的尾插法,尾插法比较直观易懂
1 void addStudent(Student s,int id) 2 { 3 Student q,p=s; 4 while(p->next != NULL) 5 { 6 p = p->next; 7 } 8 q = malloc(sizeof(Student)); 9 q->id = id; 10 q->next = NULL; 11 p->next = q; 12 s->id++; 13 }
打印节点函数,实际上就是遍历整个链表
1 void printfStudent(Student s) 2 { 3 Student p; 4 p = s; 5 while( p->next != NULL) 6 { 7 printf("id=%d; ",p->id); 8 p = p->next; 9 } 10 printf("id=%d; ",p->id); 11 }
插入节点函数
1 void insetStudent(Student s,int n,int id) 2 { 3 int i=0; 4 Student p,index; 5 p = s; 6 while( p->next != NULL && i<n) 7 { 8 p = p->next; 9 i++; 10 } 11 12 index = malloc(sizeof(Student)); 13 index->id = id; 14 index->next = p->next; 15 p->next = index; 16 s->id++; 17 }
删除节点函数
1 void deleteStudent(Student s,int n) 2 { 3 Student q,p = s; 4 int i = 1; 5 while(p->next !=NULL && i < n) 6 { 7 p = p->next; 8 i++; 9 } 10 q = p->next; 11 p->next = q->next; 12 free(q); 13 s->id--; 14 }
改节点函数
1 void changeStudent(Student s,int n,int id) 2 { 3 Student p=s; 4 int i = 0; 5 while(p->next != NULL && i < n) 6 { 7 p= p->next; 8 ++i; 9 } 10 p->id = id; 11 }
最后是主函数了,我这里进行了一一测试,头节点的id为节点总数
1 int main(void) { 2 3 Student s; 4 5 s = creatStudent(10);//创建十个节点,不包括头节点,以下都是不包括头节点 6 printfStudent(s);//打印 7 8 insetStudent(s,1,100);//在第1个位置后面插入id为100的节点 9 printfStudent(s);//打印 10 11 deleteStudent(s,1);//删除第一个节点 12 printfStudent(s);//打印 13 14 addStudent(s,888);//在末尾插入一个id为888的节点 15 printfStudent(s);//打印 16 17 changeStudent(s,1,1);//感觉第一个数据是100不合适,没理由 = =! 18 printfStudent(s);//打印 19 20 return EXIT_SUCCESS; 21 }
下面是测试的结果
1 id=10; 2 id=1; 3 id=2; 4 id=3; 5 id=4; 6 id=5; 7 id=6; 8 id=7; 9 id=8; 10 id=9; 11 id=10; 12 13 id=11; 14 id=1; 15 id=100; 16 id=2; 17 id=3; 18 id=4; 19 id=5; 20 id=6; 21 id=7; 22 id=8; 23 id=9; 24 id=10; 25 26 id=10; 27 id=100; 28 id=2; 29 id=3; 30 id=4; 31 id=5; 32 id=6; 33 id=7; 34 id=8; 35 id=9; 36 id=10; 37 38 id=11; 39 id=100; 40 id=2; 41 id=3; 42 id=4; 43 id=5; 44 id=6; 45 id=7; 46 id=8; 47 id=9; 48 id=10; 49 id=888; 50 51 id=11; 52 id=1; 53 id=2; 54 id=3; 55 id=4; 56 id=5; 57 id=6; 58 id=7; 59 id=8; 60 id=9; 61 id=10; 62 id=888;