Skip to main content

21. Merge Two Sorted Lists

https://leetcode.com/problems/merge-two-sorted-lists

Python

(This is be used in 143. Reorder List)

class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
cur1, cur2 = l1, l2
head = ListNode(val=-1)
current = head

while(cur1 and cur2):
if cur1.val > cur2.val:
current.next = cur2
cur2 = cur2.next
else:
current.next = cur1
cur1 = cur1.next
current = current.next

if cur1 is not None:
current.next = cur1

if cur2 is not None:
current.next = cur2

return head.next

Javascript

 var mergeTwoLists = function(list1, list2) {
let head = new ListNode();
let start = head;
while (list1 !== null && list2 !== null) {
if (list1.val < list2.val) {
start.next = list1;
list1 = list1.next;
} else {
start.next = list2;
list2 = list2.next;
}
start = start.next;
}
start.next = list1 === null ? list2 : list1;
return head.next;
};