Which algorithm approach is better to merge two ascending order sorted linked lists into one ascending order sorted linked list?
Time vs Space Complexity?
This solution reduces space complexity of the program since a new linked list is not created and assigned unnecessarily.
assume head1 and head2 the head nodes of lists
if(head1==null && head2==null) return null;
if(head1==null && head2!=null) return head2;
if(head1!=null && head2==null) return head1;
//assigning mergeLists head to min of both head
SinglyLinkedListNode t1, t2, c;
if(head1.data<head2.data){
t1 = head1;
t2 = head2;
c = head1;
}else{
t1 = head2;
t2 = head1;
c = head2;
}
//sorting both lists within without creating new list
while(t1.next!=null){
if(t1.next.data <= t2.data) t1 = t1.next;
else{
SinglyLinkedListNode temp = t1.next;
t1.next = t2;
t1 = t1.next;
t2 = temp;
}
}
t1.next = t2;
return c;
This one is classic recursive approach better in terms of time complexity.
assume a as head1 and b as head2
MergeSorted(Node a, Node b)
if (a == null && b == null)
return null;
if a==null
return b;
if b==null
return a;
Node c //Combined List // new list
if((a).data<(b).data)
c=a;
(c).next=MergeSorted((a).next,b);
else
c=b;
(c).next=MergeSorted(a,(b).next);
return c;
Neither of these creates a new list. c
is merely another reference to a list node, not a new object.
Your first statement, checking both lists for null
, adds nothing to the program: the immediately following if
will do the same job on its own.
Neither of these is superior in time complexity; they're each O(a+b) on the two list lengths. The differences are in clarity and maintainability. Since you haven't defined your metric for "better" in any other terms, the question is moot.