-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergelist.py
More file actions
58 lines (54 loc) · 1.49 KB
/
Copy pathmergelist.py
File metadata and controls
58 lines (54 loc) · 1.49 KB
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
#https://leetcode.com/problems/merge-two-sorted-lists/submissions/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def append(x,val):
x.next=ListNode(val)
return x.next
def convert(n):
h=ListNode(n[0])
rv=h
n=n[1:]
for e in n:
append(h,e)
h=h.next
return rv
def printll(n):
h=n
#print(h.val,end=',')
while h:
print(h.val,end=',')
h=h.next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
if list1==None and list2==None: return None
h,g=list1,list2
rv2=[]
while h and g:#maybe check for None
if h.val<g.val:
#tail=append(tail,ListNode(h.val))
rv2.append(h.val)
h=h.next
else:
#tail=append(tail,ListNode(g.val))
rv2.append(g.val)
g=g.next
while h:
#tail=append(tail,ListNode(h.val))
rv2.append(h.val)
h=h.next
while g:
#tail=append(tail,ListNode(g.val))
rv2.append(g.val)
g=g.next
#print('rv2=',rv2)
#print('rv=')
#printll(rv)
return convert(rv2)