7-51 两个有序链表序列的合并 (20 分)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL
。
输入样例:
输出样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include <stdio.h> #include <stdlib.h>
typedef int ElemType; typedef struct LNode{ ElemType Data; struct LNode *Next; }LNode, *LinkList; LinkList Read(void); LinkList Merge(LinkList La, LinkList Lb); void Print(LinkList L);
int main() { LinkList La, Lb, Lc; La = Read(); Lb = Read(); Lc = Merge(La, Lb); Print(Lc);
return 0; } LinkList Read(void){ LinkList L,rear, temp; ElemType data; L = (LinkList)malloc(sizeof(LNode)); L->Data = -1; L->Next = NULL; rear = L; scanf("%d", &data); while(data!=-1){ temp = (LinkList)malloc(sizeof(LNode)); temp->Data = data; temp->Next = NULL; rear->Next = temp; rear = rear->Next; scanf("%d", &data); } return L; }
LinkList Merge(LinkList La, LinkList Lb){ LinkList L, pa, pb, rear; L = (LinkList)malloc(sizeof(LNode)); L->Data = -1; L->Next = NULL; rear = L; pa = La->Next; pb = Lb->Next; while(pa&&pb){ if(pa->Data < pb->Data){ rear->Next = pa; pa = pa->Next; } else{ rear->Next = pb; pb = pb->Next; } rear = rear->Next; } while(pa){ rear->Next = pa; pa = pa->Next; rear = rear->Next; } while(pb){ rear->Next = pb; pb = pb->Next; rear = rear->Next; } rear->Next = NULL; return L; }
void Print(LinkList L){ LinkList p; int tag = 1; p = L->Next; while(p){ if(tag){ printf("%d", p->Data); tag = 0; p = p->Next; } else{ printf(" %d", p->Data); p = p->Next; } } if(tag){ printf("NULL"); } }
|