My solutions in 3 languages


  • 6

    The problem can be solved by recursion with simplicity.
    But it require stack size as big as the length of two lists.
    So I choose while or for loop to get through the lists.

    Java:

    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(0);
            ListNode tail = head;
            for (boolean left; l1 != null && l2 != null; tail = tail.next) {
                left = l1.val < l2.val;
                tail.next = left ? l1 : l2;
                l1 = left ? l1.next : l1;
                l2 = left ? l2 : l2.next;
            }
            tail.next = l1 != null ? l1 : l2;
            return head.next;
        }
    }
    

    C++:

    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode *head = new ListNode(0), *tail = head;
            for (bool left; l1 && l2; tail = tail->next) {
                left = l1->val < l2->val;
                tail->next = left ? l1 : l2;
                l1 = left ? l1->next : l1;
                l2 = left ? l2 : l2->next;
            }
            tail->next = l1 != NULL ? l1 : l2;
            return head->next;
        }
    };
    

    Python:

    class Solution:
        # @param two ListNodes
        # @return a ListNode
        def mergeTwoLists(self, l1, l2):
            head = ListNode(0)
            tail = head
            while l1 is not None and l2 is not None:
                left = l1.val < l2.val
                tail.next = l1 if left else l2
                tail = tail.next
                l1 = l1.next if left else l1
                l2 = l2 if left else l2.next
                tail.next = l2 if l1 is None else l1
            return head.next

  • 0
    S

    the Python solution is beautiful!


  • 1
    W

    For the above Python solution, what about the case where either of the two linked lists is None?


  • 0

    It will return None


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.