Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

merging two linked lists

ireneirene Posts: 20Member
this is the function to merge two linked lists of integers that are sorted
into ascending order...
the result is the third linked lists that is sorted combination of original
two...

please take a look and give some help thanx...

[code]
void merge(const List& a, const List& b){

Node* curr = a.head; //to traverse the first list
Node* comp = b.head; //to traverse the second list
Node* head = new ListNode; //creating the third list
Node* temp = head; //to traverse the third list

while (curr->next!=NULL && comp->next!=NULL){
// but what if there are different # of Nodes in the lists???
if (curr->item <= comp->item){
temp->item = curr->item;
curr = curr->next;
}
else {
temp->item = comp->item;
comp = comp->next;
}
temp->next = new ListNode;
temp = temp->next;
}
[/code]


Comments

  • FelixFelix Posts: 438Member
    [italic]
    // but what if there are different # of Nodes in the lists???
    [/italic]

    After the "main" while loop, you have to append these to loops:

    [code]
    [blue]while[/blue] (curr->next != NULL)
    {
    temp->item = curr->item;
    curr = curr->next;
    temp->next = [blue]new[/blue] ListNode;
    temp = temp->next;
    }

    [blue]while[/blue] (comp->next != NULL)
    {
    temp->item = comp->item;
    comp = comp->next;
    temp->next = [blue]new[/blue] ListNode;
    temp = temp->next;
    }
    [/code]

    Please not that, not only my loops but also after yours, temp->next has been created, but is unused. You would have to delete it at the end of the function.

    Was that all that was wrong with your function or was there anything else?

    ---
    [b]edx[/b] - Member of [blue][b]CodeForce[/b][/blue] (http://codeforce.d2g.com)

Sign In or Register to comment.