Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. 

The new list should be made by splicing together the nodes of the first two lists.
  • Examples:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
  • Analysis:
Merge two sorted lists until one of them is ended up.

Then merge the rest list.
  • Code - Java:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode ptr = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                ptr.next = l1;
                l1 = l1.next;
            } else {
                ptr.next = l2;
                l2 = l2.next;
            }
            ptr = ptr.next;
        }
        if (l1 != null) {
            ptr.next = l1;
        }
        if (l2 != null) {
            ptr.next = l2;
        }
        return dummy.next;
    }
}
  • Code - C++:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(-1);
        ListNode* ptr = dummy;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val <= l2->val) {
                ptr->next = l1;
                l1 = l1->next;
            } else {
                ptr->next = l2;
                l2 = l2->next;
            }
            ptr = ptr->next;
        }
        if (l1 != NULL) {
            ptr->next = l1;
        }
        if (l2 != NULL) {
            ptr->next = l2;
        }
        return dummy->next;
    }
};
  • Code - Python:
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        ptr = dummy
        while l1 != None and l2 != None:
            if l1.val <= l2.val:
                ptr.next = l1
                l1 = l1.next
            else:
                ptr.next = l2
                l2 = l2.next
            ptr = ptr.next
        if l1 != None:
            ptr.next = l1
        if l2 != None:
            ptr.next = l2
        return dummy.next
  • Time Complexity: O(M + N), M, N are the length of two sorted linked lists.

  • Space Complexity: O(1)

results matching ""

    No results matching ""