forked from yanglei-github/Leetcode_in_python3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
21_Merge Two Sorted Lists.py
65 lines (58 loc) · 1.67 KB
/
21_Merge Two Sorted Lists.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 10:29:03 2019
@author: leiya
"""
'''
0626 updated:更新新的写法
0709 l1,l2当前指向的位置是还没有比较的位置 -->参考88题
'''
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummynode = ListNode(0)
pre = dummynode
while l1 and l2:
if l1.val <= l2.val:
pre.next = l1
pre = l1
l1 = l1.next
else:
pre.next = l2
pre = l2
l2 = l2.next
if l1:
pre.next = l1
if l2:
pre.next = l2
return dummynode.next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = dummy= ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1:
cur.next = l1
else:
cur.next = l2
return dummy.next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = dummy = ListNode(0)
#must use this type because dummy and cur must be the same site at the beginning
#use dummy save the head site of listnode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next