I have a merge function of linked lists working. However, recursion is being used and I would like to change the code and make it iterative. But I did not succeed.
Follow the code:
struct Node
{
int data;
struct Node *next;
}
struct Node* MergeLists(struct Node *headA,struct Node* headB)
{
if(headA==NULL) return headB;
if(headB==NULL) return headA;
if(headA==NULL && headB==NULL) return NULL;
if(headA->data < headB->data)
{
headA->next=MergeLists(headA->next,headB);
return headA;
}
else
{
headB->next=MergeLists(headA,headB->next);
return headB;
}
}
What I got so far was this:
struct Node
{
int data;
struct Node *next;
}
Node* MergeLists(Node *headA, Node* headB)
{
if(headA==NULL) return headB;
if(headB==NULL) return headA;
if(headA==NULL && headB==NULL) return NULL;
while(headA!=NULL && headB!=NULL)
{
if(headA->data>headB->data)
{
return headB;
headB=headB->next;/*O problema está aqui preciso retornar o valor menor e ao mesmo tempo avançar a lista*/
}else
{
return headA;
headA=headA->next;/*O problema está aqui preciso retornar o valor menor e ao mesmo tempo avançar a lista com o return antes ele irá sair sem avançar*/
}
}
}
NOTE: The two lists are in ascending order.
Ex:
HeadA = 1, 3, 5.
HeadB = 2, 4, 6.
Merge = 1, 2, 3, 4, 5, 6.