diff --git a/Lecture049 Linked List Day6/mergeList.cpp b/Lecture049 Linked List Day6/mergeList.cpp index 472620ac..8e4f0201 100644 --- a/Lecture049 Linked List Day6/mergeList.cpp +++ b/Lecture049 Linked List Day6/mergeList.cpp @@ -22,50 +22,61 @@ ************************************************************/ -void solve(Node* first, Node* second) { - - - Node* curr1 = first; - Node* next1 = curr1 -> next; - - Node* curr2 = second; - Node* next2 = curr2 -> next; - - while(next1 != NULL && curr2 != NULL) { - - if( (curr2 -> data >= curr1 -> data ) - && ( curr2 -> data <= next1 -> data)) { - +Node* solve(Node* first, Node* second) { + + //if only one element is present in first list + if(first -> next == NULL) { + first -> next = second; + return first; + } + + Node* curr1 = first; + Node* next1 = curr1 -> next; + + Node* curr2 = second; + Node* next2 = curr2 -> next; + + while(next1 != NULL && curr2 !=NULL) { + + if((curr2 -> data >= curr1 -> data) + && ( curr2 -> data <= next1 -> data)) { + + //add node in between the first list curr1 -> next = curr2; + next2 = curr2 -> next; curr2 -> next = next1; + //update pointers + curr1 = curr2; curr2 = next2; } - else { - + else{ + //go one step ahead in first list + curr1 = next1; + next1 = next1 -> next; + + if(next1 == NULL) { + curr1 -> next = curr2; + return first; + } } - - } - - + return first; } Node* sortTwoLists(Node* first, Node* second) { - if(first == NULL) + if(first == NULL) return second; - + if(second == NULL) return first; - - if(first -> data <= second -> data ){ - solve(first, second); + + if(first -> data <= second -> data) { + return solve(first, second); } else { - solve(second, first); + return solve(second, first); } - - }