#include<stdio.h> #include<stdlib.h> typedef struct students { int num ; int score; students* next; }students_t; students_t* sort_create(int chain); //创建链表,并升序排列 students_t* insert(students_t* head, students_t*p); //在链表中插入节点 void print(students_t* head); //将链表中的数据打印出来 void deletechain(students_t* head); //将链表占用的地址释放 int main() { students_t *head_n = 0,*head_m = 0,*temp; int n ,m; scanf("%d%d",&n,&m); //输入链表的长度 head_n = sort_create(n); head_m = sort_create(m); while(head_m) { temp = head_m; head_m = head_m -> next; head_n = insert(head_n,temp); //head_m = head_m -> next; 放在这里会由于上一个步骤->next被改变所以要放在insert之前,先移动到下一个节点,所以head_m链表也被上个步骤破坏了,之后不能再使用了。 }//将m链表插入到n的链表中 print(head_n); deletechain(head_n);//由于被合并了所以释放head_n就可以了。 return 0; } students_t* insert(students_t* head, students_t*p) { students_t* p1,*p2; if(head ==0) //空链表 { head = p; p -> next = 0; return head; } if(p->num < head ->num) //插入链表头部 { p->next = head; head = p; return head; } p2 = p1 = head; while(p2-> next != 0 && p2->num < p-> num) //寻找插入位置 { p1 = p2; p2 = p2->next; } if(p2->num < p->num) //插入链表尾部 { p2->next = p; p->next = 0; } else //插入p1,p2之间 { p1->next =p; p->next = p2; } return head; } students_t* sort_create(int chain) { students_t *head,*p1; head = 0; int num,score; while(chain) { scanf("%d%d",&num,&score); p1 = (students_t*)malloc(sizeof(students_t)); p1 ->num = num; p1 ->score = score; head = insert(head,p1);//链表数据按照升序一个个插入 chain--; } return head; } void print(students_t* head) { students_t* p1; p1 = head; while(p1 != 0) { printf("%d %d\n",p1 ->num,p1->score); p1 = p1 -> next; } if(head == 0) { printf("This link list is empty!\n"); } } void deletechain(students_t* head) { students_t* p1; while(head) { p1 = head; head = head->next; free(p1); } }
由于没有学过链表,花了两天学习后写的代码和大家一起学习。
0.0分
3 人评分
C语言训练-求具有abcd=(ab+cd)2性质的四位数 (C语言代码)浏览:619 |
计算质因子 (C++代码)浏览:1824 |
WU-输出正反三角形 (C++代码)浏览:1098 |
IP判断 (C语言代码)浏览:819 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:624 |
幸运数 (C++代码)浏览:1309 |
C二级辅导-公约公倍 (C语言代码)浏览:537 |
C二级辅导-阶乘数列 (C语言代码)浏览:583 |
C语言程序设计教程(第三版)课后习题6.7 (C语言代码)浏览:725 |
C语言程序设计教程(第三版)课后习题7.2 (C语言代码)浏览:812 |