Skip to content

Commit 5e669b9

Browse files
committed
21 Update
1 parent 8617d46 commit 5e669b9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

linkedlist/MergeTwoSortedLists.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Yu Zhou
2+
# 21. Merge Two Sorted Lists
3+
# 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
4+
5+
6+
#思路
7+
#因为是sorted,只需要设置一个guard_node用来之后的return
8+
#就可以设置一个新的Linkedlist的Node,然后用来储存
9+
#比对完了的值,最后返回guard_node.next(跳过第一个dummy node)就行了
10+
11+
class Solution(object):
12+
def mergeTwoLists(self, n1, n2):
13+
#Edge
14+
if not n1 and not n2:
15+
return None
16+
17+
node = guard_node = ListNode(0)
18+
19+
while n1 and n2:
20+
if n1.val <= n2.val:
21+
node.next = n1
22+
n1 = n1.next
23+
else:
24+
node.next = n2
25+
n2 = n2.next
26+
node = node.next
27+
#Edge
28+
if n1 or n2:
29+
node.next = n1 or n2
30+
31+
return guard_node.next

0 commit comments

Comments
 (0)