7-2 两个有序链表序列的合并
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1 2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
解题思路
首先编写链表结构体,并创建并读入两个链表,在编写CombineList(List L1, List L2)函数,将两个链表合并。其中ComebineList()函数是创建一个新链表,同时比较两个链表对应的元素的大小,写入新链表最后返回该链表。
代码
#include<stdio.h> #include<stdlib.h> typedef int ElemType; typedef struct LNode { ElemType Data; struct LNode * Next; }LNode, *List; List CreateList() { List head, L, pro; int n; L = (List)malloc(sizeof(struct LNode)); head = L; scanf("%d", &n); if (n == -1) // 第一个是-1就直接返回NULL { L = NULL; return L; } while (1) { if (n == -1) { //序列结束符号 pro->Next = NULL; //序列尾指向NULL free(L); //释放多余节点 return head; } L->Data = n; L->Next = (List)malloc(sizeof(LNode)); pro = L; L = L->Next; scanf("%d", &n); } } List CombineList(List L1, List L2) { List L, head; L = (List)malloc(sizeof(LNode)); head = L;// 建立新节点 while (L1&&L2) { // 进行挨个比较 if (L1->Data <= L2->Data) { L->Next = L1; L = L->Next; L1 = L1->Next; } else { L->Next = L2; L = L->Next; L2 = L2->Next; } } if (L1) // L2进行到空或者L2初始为空 { L->Next = L1; L = head; head = head->Next; free(L); return head; } else if (L2) // L1进行到空或者L1初始为空 { L->Next = L2; L = head; head = head->Next; free(L); return head; } else //两者初始皆为空 return NULL; } int main() { List L, L1, L2; int m, n, i; L1 = CreateList(); L2 = CreateList(); L = CombineList(L1, L2); if (!L) printf("NULL"); //链表为空时输出NULL else { while (L->Next) { printf("%d ", L->Data); L = L->Next; } printf("%d", L->Data); } return 0; }