I have a doubt in a question on "Merge 2 sorted linked lists" .
I tried really hard before posting, i tested on paper many times - it comes out correct, but there is something wrong with my code.
Basically, i am not getting the recursion right.
Also, is there some software/tool where i can see the interiors of the stack when recursion is going on?
My code is as follows
Code:
#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node* link;
}Node;
Node* start1;
Node* start2;
Node* start;
Node* node;
Node* result;
int main(void)
{
printf("\nEnter the elements of the first ll , Enter -1 to stop entering data");
start1=form();
printf("\nEnter the elements of the second ll , Enter -1 to stop entering data");
start2=form();
printf("\nLinked list 1 contents are ");
display(start1);
printf("\nLinked list 2 contents are ");
display(start2);
start=NULL;
merge(start1,start2);
display(start);
printf("\nThe value stored in result = %d",result->data);
getch();
return 0;
}
int merge(Node* node1, Node* node2)
{
if(node1==NULL)
return node2;
if(node2==NULL)
return node1;
if(node1!=NULL && node2!=NULL)
{
if(node1->data <= node2->data)
{
if(start == NULL)
start = node1;
result=node1;
result->link = merge(node1->link,node2);
}
else
{
if(start == NULL)
start=node2;
result=node2;
result->link = merge(node1,node2->link);
}
return result;
}
//return result;
}
int display(Node* node)
{
while(node)
{
printf("%d ",node->data);
node = node->link;
}
}
int form()
{
int num=0;
Node* ptr;
Node* last;
Node* start=NULL;
start=NULL;
while(1)
{
scanf("%d",&num);
if(num == -1)
{
printf("Linked list formation over ");
return start;
}
else
{
ptr=(Node*)malloc(sizeof(Node));
ptr->data = num;
ptr->link = NULL;
if(start == NULL)
{
start=ptr;
last=ptr;
}
else
{
last->link = ptr;
last=ptr;
}
}
}
}
Thanks
Aftab