The code doesn't work until I dynamically allocate the memory for pointer C in merge_List function.
If I uncomment list c = (list)malloc(sizeof(Node));
and comment
list c;
, the code works.
I don't know why. Can anyone explain to me?
The code is very straightforward, so not much comment.
Thank you!
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
struct Node *next;
int value;
}Node,*list;
list create_Node()
{
list head = (list)malloc(sizeof(Node));
if(!head) exit(-1);
list tail = head;
int len;
int val;
printf("Please enter the length of the list:\n ");
scanf("%d",&len);
for(int i=0;i<len;i++)
{
list new = (list)malloc(sizeof(Node));
if(!new) exit(-1);
printf("Please enter the value of the node:\n ");
scanf(" %d",&val);
new->value=val;
tail->next= new;
tail =new;
}
return head;
}
list merge_list(list a, list b)
{
if(a==NULL||b==NULL) exit(-1);
//list c = (list)malloc(sizeof(Node));
list c;
list d = c;
while(a&&b)
{
if(a->value<=b->value)
{
c->next=a;
c=a;
a=a->next;
}
else
{
c->next = b;
c=b;
b=b->next;
}
}
c->next = a?a:b;
return d;
}
int main() {
list l = create_Node();
l=l->next;
list j = create_Node();
j=j->next;
list n =merge_List(l,j);
n=n->next;
while(n)
{
printf("%d\n",n->value);
n=n->next;
}
return 0;
}