# My solutions in 3 languages

• 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``````

• the Python solution is beautiful!

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

• It will return None

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