Popular Posts

Sunday, March 27, 2011

Merge two Sorted Linked lists

Given two sorted Linked Lists, we need to merge them into the third list in sorted order. Complexity – O(n)
public static Node mergeList(Node a, Node b) {
Node result = null;
if (a == null)
return b;
if (b == null)
return a;

if (a.value <= b.value) {
result = a;
result.next = mergeList(a.next, b);
} else {
result = b;
result.next = mergeList(b.next, a);
}
return result;
}

No comments:

Post a Comment