-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeTwoLists.py
More file actions
53 lines (45 loc) · 994 Bytes
/
mergeTwoLists.py
File metadata and controls
53 lines (45 loc) · 994 Bytes
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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(l1, l2):
def getNext(l1, l2):
if l1 and l2:
return l1.val < l2.val
return True if l1 else False
if not l1 and not l2:
return None
ret = getNext(l1, l2)
if ret:
l = head = l1
l1 = l1.next
else:
l = head = l2
l2 = l2.next
while l1 or l2:
ret = getNext(l1, l2)
if ret:
l.next = l1
l1 = l1.next
else:
l.next = l2
l2 = l2.next
l = l.next
return head
a = ListNode(1)
b = ListNode(2)
c = ListNode(4)
a.next = b
b.next = c
d = ListNode(3)
e = ListNode(5)
d.next = e
l = mergeTwoLists(a, d)
assert l.val == 1
assert l.next.val == 2
assert l.next.next.val == 3
assert l.next.next.next.val == 4
assert l.next.next.next.next.val == 5