-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21_merge2SortedLLists.py
81 lines (61 loc) · 1.92 KB
/
21_merge2SortedLLists.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 21. Merge Two Sorted Lists
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
l = ListNode(0)
p_list = l
p1 = l1
p2 = l2
while p1 and p2:
if p1.val==p2.val:
p_list.next = ListNode(p1.val)
p_list = p_list.next
p_list.next = ListNode(p2.val)
p_list = p_list.next
p1 = p1.next
p2 = p2.next
elif p1.val<p2.val:
p_list.next = ListNode(p1.val)
p_list = p_list.next
p1 = p1.next
elif p2.val<p1.val:
p_list.next = ListNode(p2.val)
p_list = p_list.next
p2 = p2.next
if p1 or p2:
p_list.next = p1 or p2
return l.next
'''
p1 = l1
p2 = l2
l = []
while p1 and p2:
if p1.val>p2.val:
l+=[p2.val]
p2 = p2.next
elif p1.val<p2.val:
l+=[p1.val]
p1 = p1.next
elif p1.val==p2.val:
l+=[p1.val, p2.val]
p1 = p1.next
p2 = p2.next
if p1:
while p1:
l.append(p1.val)
p1 = p1.next
elif p2:
while p2:
l.append(p2.val)
p2 = p2.next
ll = ListNode()
pll = ll
for i in l:
pll.next = ListNode(i)
pll = pll.next
return ll.next
'''