已有两个链表,每个链表中的结点包括学号,成绩。要求把两个链表合并,按学号升序排列。
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #define N 10 typedef struct student { int num; float score; struct student *next; }stu; stu *creat() { int i; stu *p, *head = NULL, *tail = head; for (i = 0; i < N; i++) { p = (stu *)malloc(sizeof(stu)); scanf("%d,%f", &p->num, &p->score); p->next = NULL; if (p->num <= 0) { free(p); break; } if (head == NULL) head = p; else tail->next = p; tail = p; } return head; } void print(stu *p) { while (p != NULL) { printf("%d %.2f ", p->num, p->score); p = p->next; } } stu *link(stu *p1, stu *p2) { stu *p, *head; if (p1->num < p2->num) { head = p = p1; p1 = p1->next; } else { head = p = p2; p2 = p2->next; } while ((p1 != NULL) && (p2 != NULL)) { if (p1->num < p2->num) { p->next = p1; p = p1; p1 = p1->next; } else { p->next = p2; p = p2; p2 = p2->next; } } if (p1 != NULL) p->next = p1; else p->next = p2; return head; } int main() { stu *a, *b, *c; printf(" 请输入链表a的信息,学号小于等于零时结束输入:格式(学号,成绩) "); a = creat(); printf(" 请输入链表b的信息,学号小于等于零时结束输入:格式(学号 成绩) "); b = creat(); printf(" 链表a的信息为: "); print(a); printf(" 链表b的信息为: "); print(b); c = link(a, b); printf(" 合并后的链表信息为: "); print(c); return 0; }