Merge two sorted linked lists

  • + 0 comments

    SinglyLinkedListNode* mergeLists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {

    if(head1 ==nullptr) { return head2; }

    if(head2 == nullptr) { return head1; }

    stack temp; while (head1 != nullptr && head2 != nullptr ) {

    if(head1->data <= head2->data)
    {
    
       temp.push(head1->data );
       head1 = head1->next;
    
    }else {
       temp.push(head2->data );
       head2 = head2->next;
    
    }
    

    }

    while (head1 != nullptr) { temp.push(head1->data );

            head1 = head1->next;
    

    }

    while (head2 != nullptr) { temp.push(head2->data );

    head2 = head2->next;
    

    }

    SinglyLinkedListNode* res = nullptr;

    while(!temp.empty()){

    int tp = temp.top();
    
    temp.pop();
    

    SinglyLinkedListNode *temp = new SinglyLinkedListNode(tp); temp->next = res; res = temp; }

    return res;

    }