单链表的合并还是挺简单的,直接上代码吧。
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 链表读取 */
void Print( List L ); /*链表输出;空链表将输出NULL */
List Merge( List L1, List L2 ); /*链表合并*/
int main()
{
List L1, L2, L;
L1 = Read(); //读取链表1
L2 = Read(); //读取链表2
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
List Merge( List L1, List L2 )
{
List L, p1, p2, r ;
p1 = L1->Next;
p2 = L2->Next;
L = (List)malloc(sizeof(struct Node));
L->Next = NULL;
r = L;
while (p1 && p2){
if(p1->Data < p2->Data){
r->Next = p1;
r = p1;
p1 = p1->Next;
}
else{
r->Next = p2;
r = p2;
p2 = p2->Next;
}
}
if(p1)
r->Next = p1;
else
r->Next = p2;
L1->Next = NULL;
L2->Next = NULL;
return L;
}
List Read()
{
int n, i;
List L, p, s;
scanf("%d",&n);
L = (List)malloc(sizeof(struct Node));
L->Next = NULL;
p = L;
for(i = 0;i < n; ++i){
s = (List)malloc(sizeof(struct Node));
scanf("%d",&s->Data);
s->Next = p->Next;
p->Next = s;
p = s;
}
return L;
}
void Print(List L)
{
List p;
p = L->Next;
if (L->Next==NULL)
{
printf("NULL");
}
while(p)
{
printf("%d ", p->Data);
p = p->Next;
}
printf("\n");
}