#include
#include
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(int a[],int n); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表;空链表将输出NULL */
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
int l1[5] = {2,4,6,8,10};
int l2[5] = {2,4,6,8,10};
L1 = Read(l1,5);
L2 = Read(l2,5);
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
void Print( List L )
{
List p = L->Next;
if(!p){
printf("NULL\n");
}
else{
while (p) {
printf("%d ",p->Data);
p = p->Next;
}
printf("\n");
}
}
List Read(int a[],int n)
{
List head = (List)malloc(sizeof(List));
head->Data = n;
head->Next = NULL;
int i;
List p,last;
last = head;
for (i = 0; i < n; i++) {
p = (List)malloc(sizeof(List));
p->Data = a[i];
p->Next = NULL;
last->Next = p;
last = p;
}
return head;
}
List Merge( List L1, List L2 )
{
List head,tail;
head = (List)malloc(sizeof(struct Node));
tail = head;
head->Next = NULL;
head->Data = L1->Data + L2->Data;
List p,q;
p = L1->Next;
q = L2->Next;
while (p && q)
{
if(p->Data > q->Data)
{
tail->Next = q;
tail = q;
q = q->Next;
}
else if(p->Data < q->Data)
{
tail->Next = p;
tail = p;
p = p->Next;
}
else
{
tail->Next = p;
tail = p;
p = p->Next;
tail->Next = q;
tail = q;
q = q->Next;
}
}
while (p)
{
tail->Next = p;
tail = p;
p = p->Next;
}
while (q)
{
tail->Next = q;
tail = q;
q = q->Next;
}
L1->Next = NULL;
L2->Next = NULL;
return head;
}