Q: Merge two linked list, and return merged List and two empty lists.
Input:
3
1 3 5
5
2 4 6 8 10
Desired Output:
1 2 3 4 5 6 8 10
NULL
NULL
But I got:
1 2 3 4 5 6 8 10
1 3 5
2 4 6 8 10
My code:
#include <stdio.h>
#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 );
List Merge( List L1, List L2 );
void C(List L);
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
C(L1);
Print(L1);
Print(L2);
return 0;
}
void C(List L){
L = L->Next;
}
List Merge( List L1, List L2 ){
List prehead = (List)malloc(sizeof(struct Node));
List t = prehead;
while(L1&&L2){
if(L1->Data < L2->Data){
List node = (List)malloc(sizeof(struct Node));
node->Data = L1->Data;
t->Next = node;
t = t->Next;
L1 = L1->Next;
}
else{
List node = (List)malloc(sizeof(struct Node));
node->Data = L2->Data;
t->Next = node;
t = t->Next;
L2 = L2->Next;
}
}
while(L1){
List node = (List)malloc(sizeof(struct Node));
node->Data = L1->Data;
t->Next = node;
t = t->Next;
L1 = L1->Next;
}
while(L2){
List node = (List)malloc(sizeof(struct Node));
node->Data = L2->Data;
t->Next = node;
t = t->Next;
L2 = L2->Next;
}
t->Next = NULL;
return prehead->Next;
}
List Read(){
int n;
scanf("%d",&n);
List prehead = (List)malloc(sizeof(struct Node));
List L = prehead;
if(n==0) return NULL;
for(int i=0; i<n; i++)
{
List node = (List)malloc(sizeof(struct Node));
scanf("%d",&node->Data);
L->Next = node;
L = L->Next;
}
List node = prehead;
List head = prehead->Next;
free(node);
L->Next = NULL;
return head;
}
void Print(List L){
if(!L) printf("NULL");
List p = L;
int flag = 0;
while(p){
if(!flag)
flag = 1;
else
printf(" ");
printf("%d",p->Data);
p = p->Next;
}
printf("\n");
}
Everything works well in function. But in the main, it does not change anything.