Original title Link: http://oj.leetcode.com/problems/merge-two-sorted-lists/
This topic is relatively simple, classic linked list basic operation. Maintaining the two pointers corresponds to two linked lists, because it is generally based on a linked list, such as L1, then if the L1 of the element is relatively small, then move the L1 directly, otherwise L2 the current element into the L1 of the current element before. Algorithm time complexity is O (m+n), M and N are two linked list length, space complexity is O (1), the code is as follows:
Public ListNode mergetwolists (listnode L1, ListNode L2) {
ListNode helper = new ListNode (0);
ListNode pre = helper;
Helper.next = L1;
while (l1!=null && L2!= null)
{
if (l1.val>l2.val)
{
ListNode next = l2.next;
L2.next = Pre.next;
Pre.next = L2;
L2 = Next;
else
{
L1 = l1.next;
}
Pre = Pre.next;
}
if (l2!=null)
{
pre.next = L2;
}
return helper.next;
}
This problem is similar to the merge Sorted Array, except that the latter is a combined operation of an array, which may be asked together in an interview. Extended topic Merge K Sorted Lists, this is a more useful in the distributed system of basic operations, or need to pay attention to, interview can emit a lot of problems.