loveBabbar / CodeHelp-DSA-Busted-Series

This repo is creating providing students easy access to all the programs taught under Codehelp's DSA Busted Series.
3.36k stars 2.4k forks source link

lecture 49 question2: merge 2 sorted list code is not correct and incomplete #554

Open PrinceJHAjee opened 2 months ago

PrinceJHAjee commented 2 months ago

the corrected code:

include <bits/stdc++.h>

/****

Following is the linked list node structure.

template <typename T>
class Node {
    public:
    T data;
    Node* next;

    Node(T data) {
        next = NULL;
        this->data = data;
    }

    ~Node() {
        if (next != NULL) {
            delete next;
        }
    }
};

****/

Node solve(Node first, Node* second) {

  //check first LL have only one node

if(first -> next == NULL){

    first -> next = second;

    return first;

}

Node<int>* curr1 = first;
Node<int>* next1 = curr1 -> next;

Node<int>* curr2 = second;
Node<int>* next2 = curr2 -> next;

while(next1 != NULL && curr2 != NULL) {

    if( (curr2 -> data >= curr1 -> data ) 
       && ( curr2 -> data <= next1 -> data)) {

      curr1 -> next = curr2;
        next2 = curr2->next; // Update next2 before moving curr2
        curr2 -> next = next1;

        // Move curr1 to curr2, which is now the last merged node
        curr1 = curr2;
        curr2 = next2;
    }
     else{
         // move curr1 and next1

         curr1=next1;
         next1=next1->next;

         if(next1==NULL){
             curr1->next=curr2;
             return first;
         }
     }

}
return first;

}

Node sortTwoLists(Node first, Node* second) { // Write your code here. if(first == NULL) return second;

if(second == NULL)
    return first;

if(first -> data <= second -> data ){
    return solve(first, second);
}
else
{
    return solve(second, first);
}

}