In the Leetcode Merge Two Sorted Lists problem solution in Python programming You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Leetcode Merge Two Sorted Lists problem solution in Python programming
class Solution(object):
def mergeTwoLists(self, list1, list2):
if not list1: return list2
if not list2: return list1
dummy = prev = ListNode(-1)
dummy.next = list1
n1, n2 = list1, list2
while n1 and n2:
if n1.val < n2.val:
if not n1.next: n1.next = n2; break
prev, n1 = n1, n1.next
else:
tmp = n2.next
prev.next = n2
n2.next = n1
prev = n2
n2 = tmp
return dummy.next
Also read,
- Leetcode Merge Two Sorted Lists problem solution in C++
- Leetcode Merge Two Sorted Lists problem solution in Java
- Leetcode Merge Two Sorted Lists problem solution in C
- Leetcode Merge Two Sorted Lists problem solution in C#