-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_two_lists.py
65 lines (58 loc) · 1.85 KB
/
merge_two_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
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode()
cur = head
l_head = l1
r_head = l2
prev = None
while l_head or r_head:
prev = cur
if l_head:
if r_head:
if l_head.val < r_head.val:
cur.val = l_head.val
cur.next = ListNode()
cur = cur.next
l_head = l_head.next
else:
cur.val = r_head.val
cur.next = ListNode()
cur = cur.next
r_head = r_head.next
else:
cur.val = l_head.val
cur.next = ListNode()
cur = cur.next
l_head = l_head.next
if r_head:
if l_head:
if l_head.val < r_head.val:
cur.val = l_head.val
cur.next = ListNode()
cur = cur.next
l_head = l_head.next
else:
cur.val = r_head.val
cur.next = ListNode()
cur = cur.next
r_head = r_head.next
else:
cur.val = r_head.val
cur.next = ListNode()
cur = cur.next
r_head = r_head.next
if prev:
prev.next = None
else:
return None
return head