全部代码
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read();
List Read(){
int n,a;
List head,tail,p;
head = (List)malloc(sizeof(struct Node));
tail = head;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a);
p = (List)malloc(sizeof(struct Node));
p->Data = a;
p->Next = NULL;
tail->Next = p;
tail = p;
}
return head;
}
void Print( List L );
void Print( List L){
if(L->Next==NULL){
printf("NULL\n");
return ;
}
List temp = L->Next;
while(temp){
printf("%d ",temp->Data);
temp = temp->Next;
}
printf("\n");
}
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
List Merge( List L1, List L2 ){
struct Node *newlist,*temp1,*temp2,*p,*newtemp;
newlist = (struct Node *)malloc(sizeof(struct Node));
newlist->Next = NULL;
newlist->Data = 0;
newtemp = newlist;
temp1 = L1->Next,temp2 = L2->Next;
while(temp1!=NULL || temp2!=NULL){
if(temp1==NULL||temp2==NULL){
if(temp1==NULL){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp2->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp2 = temp2->Next;
}
else if(temp2==NULL){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp1->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp1 = temp1->Next;
}
}
else if(temp1->Data < temp2->Data){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp1->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp1 = temp1->Next;
}
else if(temp2->Data <= temp1->Data){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp2->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp2 = temp2->Next;
}
}
L1->Next = NULL,L2->Next = NULL;
return newlist;
}
提交代码
List Merge( List L1, List L2 ){
struct Node *newlist,*temp1,*temp2,*p,*newtemp;
newlist = (struct Node *)malloc(sizeof(struct Node));
newlist->Next = NULL;
newlist->Data = 0;
newtemp = newlist;
temp1 = L1->Next,temp2 = L2->Next;
while(temp1!=NULL || temp2!=NULL){
if(temp1==NULL||temp2==NULL){
if(temp1==NULL){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp2->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp2 = temp2->Next;
}
else if(temp2==NULL){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp1->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp1 = temp1->Next;
}
}
else if(temp1->Data < temp2->Data){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp1->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp1 = temp1->Next;
}
else if(temp2->Data <= temp1->Data){
p = (struct Node *)malloc(sizeof(struct Node));
p->Data = temp2->Data;
p->Next = NULL;
newtemp->Next = p;
newtemp = p;
temp2 = temp2->Next;
}
}
L1->Next = NULL,L2->Next = NULL;
return newlist;
}