Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
PrinceJHAjee opened this issue Aug 16, 2024 · 0 comments

Comments

@PrinceJHAjee
Copy link

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);
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant