Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview Question: Merge two sorted singly linked lists without creating new nodes

This is a programming question asked during a written test for an interview. "You have two singly linked lists that are already sorted, you have to merge them and return a the head of the new list without creating any new extra nodes. The returned list should be sorted as well"

The method signature is: Node MergeLists(Node list1, Node list2);

Node class is below:

class Node{     int data;     Node next; } 

I tried many solutions but not creating an extra node screws things. Please help.

Here is the accompanying blog entry http://techieme.in/merging-two-sorted-singly-linked-list/

like image 916
dharam Avatar asked May 22 '12 17:05

dharam


People also ask

How do you combine two sorted linked lists?

The new list should be made by splicing together the nodes of the first two lists. For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20.

How do you combine two singly linked lists?

We just need to follow some very simple steps and the steps to join two lists (say 'a' and 'b') are as follows: Traverse over the linked list 'a' until the element next to the node is not NULL. If the element next to the current element is NULL (a->next == NULL) then change the element next to it to 'b' (a->next = b).

Can you merge sort a singly linked list?

function will sort a linked list using the merge sort algorithm. to cut the list from the middle node into two halves. Eventually, we sort each part separately, then we'll merge them to get a single sorted list.

What would be the time complexity of the process of merging a sorted LinkedList?

Time Complexity: O(M+N), At every call of recursion, we are adding one node to the output.


1 Answers

Node MergeLists(Node list1, Node list2) {   if (list1 == null) return list2;   if (list2 == null) return list1;    if (list1.data < list2.data) {     list1.next = MergeLists(list1.next, list2);     return list1;   } else {     list2.next = MergeLists(list2.next, list1);     return list2;   } } 
like image 131
Stefan Haustein Avatar answered Sep 21 '22 17:09

Stefan Haustein