1. 程式人生 > >單鏈表的合並

單鏈表的合並

大小 stdlib.h -c andro lin printf 指針 type free

要求:講兩個有序鏈表合並成一個有序鏈表,結果鏈表仍使用原來兩個鏈表的存儲空間,不占用其他存儲空間,表中允許有重復的數據。

算法:(1)指針pa和pb初始化,分別指向連個鏈表La和Lb的第一個節點

   (2)Lc的結點取值為La的頭結點

   (3)指針pc初始化,指向Lc的頭結點

   (4)當指針Pa和Pb均未達到相應表尾時,則依次比較pa和pb所指向元素大小,從La或Lb中取出較小的結點插入到c的最後

   (5)將非空表的剩余段插入到pc所指結點之後,並釋放Lb的頭結點

如圖:這是算法1-3步之後結果

技術分享

程序:

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//建立一個空鏈表
int InitList_L(LinkList &L){
L=(LinkList)malloc(sizeof(LNode));
if(!L){
exit(OVERFLOW);
}
L->next=NULL;
return OK;
}

int CreateList_L(LinkList &L,int n){
LinkList p,q;
int i;
printf("Input the datas in increasing order:");
q=L;
for(i=0;i<n;i++){
p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=q->next;
// p->next=L->next;
q->next=p;
q=p;
}
return OK;
}
int MergeList_L(LinkList &La,LinkList &Lb,LinkList &Lc){


LinkList pa,pb,pc;
pa=La->next;//初始化pa的初值指向表La的第一個結點
pb=Lb->next;
Lc=pc=La;//用La的頭結點作為Lc的頭結點,pc的初值指向Lc的頭結點
while(pa && pb){ //當兩個表非空,依次取出兩表中較小的結點插入到Lc表的最後
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 OK;
}
int TraverseList_L(LinkList L){
LinkList p;
p=L->next;
while(p){
printf("%d",p->data);
p=p->next;
}
return OK;

}
main(){
int n;
LinkList La,Lb,Lc;
InitList_L(La);
InitList_L(Lb);
printf("Input the length of the list La:");
scanf("%d",&n);
CreateList_L(La,n);
printf("Input the length of the list Lb:");
scanf("%d",&n);
CreateList_L(Lb,n);
MergeList_L(La,Lb,Lc);
printf("Output the data in Lc:");
TraverseList_L(Lc);
printf("\n");
}
結果:

[email protected]:~/work/c/danlianbiao$ ./mergelist
Input the length of the list La:3
Input the datas in increasing order:1 3 5
Input the length of the list Lb:4
Input the datas in increasing order:2 4 6 8
Output the data in Lc:1234568


單鏈表的合並