Reputation: 65
Below code is not working... I'm trying to merge 2 linked-lists using iterative function.. but it is not giving desired output..it is printing elements infinitely i'm learning programming.. help me out... thanks in advance...
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}list_node;
list_node* MergeLists(list_node *headA, list_node* headB)
{
if (headA == NULL && headB == NULL) {
return NULL;
}
if (headA == NULL) {
return headB;
}
if (headB == NULL) {
return headA;
}
if (headA->data > headB->data) {
list_node *tmp = headB;
headB = headA;
headA = tmp;
}
list_node *listHead = headA;
while (headB) {
while (headA->next != NULL &&
headB->data > headA->next->data) {
headA = headA->next;
}
list_node* nextB = headB->next;
headB->next = headA->next;
headA->next = headB;
headB = nextB;
}
return listHead;
}
list_node* push(list_node* head_r, int new_data)
{
list_node* new_Node = (list_node*)malloc(sizeof(list_node));
new_Node->data = new_data;
new_Node->next = head_r;
head_r = new_Node;
return head_r;
}
void Print(list_node* head_r)
{
while(head_r)
{
printf("%d\n", head_r->data);
head_r = head_r->next;
}
}
int main()
{
list_node* l_list = NULL;
list_node* l_list2 = NULL;
l_list = push(push(push(push( push(l_list, 1),2),3),4),5);
l_list2 = push(push(push(push( push(l_list, 6),8),3),4),0);
MergeLists(l_list, l_list2);
printf("Merge 2 Sorted list \n");
Print(l_list);
return 0;
}
Upvotes: 0
Views: 44
Reputation: 624
In
if (headA->data > headB->data) {
list_node *tmp = headB;
headB = headA;
headA = tmp;
}
should be
if (headA->data > headB->data) {
list_node *tmp = headB;
headB = headA;
headA = *tmp; //tmp is a pointer
}
And in
l_list2 = push(push(push(push( push(l_list, 6),8),3),4),0);
should be
l_list2 = push(push(push(push( push(l_list2, 6),8),3),4),0); //l_list2
Upvotes: 0
Reputation: 355
You have a typo on this line l_list2 = push(push(push(push( push(l_list, 6),8),3),4),0);
I assume it's supposed to be l_list2 = push(push(push(push( push(l_list2, 6),8),3),4),0);
What happened is that you now have 2 variables pointing to the same list. When you then do the merge you try to merge the list into itself. Because with every step of the merge algorithm your list gets bigger, it never finishes.
Upvotes: 1