简繁EN

LeetCodeNo. 021

[LeetCode with Python] 21. Merge Two Sorted Lists

Contents

Problem

Problem page: https://leetcode.com/problems/merge-two-sorted-lists/
Topics: Linked List
Difficulty: Easy
Similar problems: (H) Merge k Sorted Lists, (E) Merge Sorted Array, (M) Sort List, (M) Shortest Word Distance II

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.


Analysis

Merging two sorted linked lists is a common data structures exercise in college. Start with two pointers, one at the head of each list. At each step, append the node with the smaller value to the tail of the merged list. When you reach the end of one list, don't forget to append all the remaining nodes from the other list in order (you can just attach the rest of that list to the tail of the merged list).


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
if None == l1 and None == l2:
return None
elif None == l1:
return l2
elif None == l2:
return l1

new_list = ListNode(0)
cur = new_list
node1 = l1
node2 = l2
while None != node1 and None != node2:
if node1.val < node2.val:
cur.next = node1
node1 = node1.next
else:
cur.next = node2
node2 = node2.next
cur = cur.next
if None != node1:
cur.next = node1
else:
cur.next = node2

return new_list.next

Article link: https://xnerv.wang/en/leetcode-merge-two-sorted-lists/