有序表的合併-用連結串列操作
阿新 • • 發佈:2021-10-16
我亦無他,惟手熟爾/* 有序表的合併---用連結串列實現 */ #include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef int ElemType; typedef struct Lnode{ ElemType data; struct Lnode * next; }LNode, * LinkList; void CreateList_R(LinkList * L){ int len; printf("請輸入要建立的連結串列節點個數:"); scanf("%d", &len); *L = (LinkList)malloc(sizeof(LNode) * len); int i; int val; LinkList r; r = *L; for(i = 0; i < len; i++){ printf("請輸入第%d個節點存入的值:\n", i + 1); scanf("%d", &val); LinkList s = (LinkList)malloc(sizeof(LNode)); s->data = val; s->next = NULL; r->next = s; r = s; } } void traverse_list(LinkList L){ LinkList p = L->next; while(p){ printf("%d ", p->data); p = p->next; } } /* 有序表合併---用連結串列實現 */ LinkList MergeList_L(LinkList La, LinkList Lb){ LinkList Lc; LinkList pa = La->next; LinkList pb = Lb->next; Lc = La; LinkList pc = La; while(pa && pb){ if(pa->data <= pb->data){ pc->next = pa; pc = pa; pa = pa->next; }else{ pc->next = pb; pc = pb; pb = pb->next; } } pc->next = pa?pa:pb; free(Lb); return Lc; } int main(){ LinkList La; LinkList Lb; LinkList Lc; CreateList_R(&La); CreateList_R(&Lb); Lc = MergeList_L(La, Lb); traverse_list(Lc); return 0; }