0
I have a chained list merge function working. However, recursion is being used and I would like to change the code and iterate. But I was unsuccessful.
Follows 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’ve got so far is 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.
Mixing = 1, 2, 3, 4, 5, 6.
Mixture "ordered"? If the two lists are previously ordered, the new one is then ordered?
– Jefferson Quesado
Hello @Jeffersonquesado yes they are previously ordered, the new one will be ordered. But in case only have to return the smaller one until you finish the list. Type so compares Heada with headB, if headA is smaller returns headA and then has to be headB obligatorily, then advance the list and compare again.
– Maurício Z.B