Skip to content

Commit a9e007e

Browse files
committedMar 27, 2015
merge two nodelists
1 parent d9d3017 commit a9e007e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
 

Diff for: ‎mergeTwoLists.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Definition for singly-linked list.
2+
class ListNode:
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
# @param two ListNodes
8+
# @return a ListNode
9+
def mergeTwoLists(l1, l2):
10+
def getNext(l1, l2):
11+
if l1 and l2:
12+
return l1.val < l2.val
13+
return True if l1 else False
14+
15+
if not l1 and not l2:
16+
return None
17+
18+
ret = getNext(l1, l2)
19+
if ret:
20+
l = head = l1
21+
l1 = l1.next
22+
else:
23+
l = head = l2
24+
l2 = l2.next
25+
26+
while l1 or l2:
27+
ret = getNext(l1, l2)
28+
if ret:
29+
l.next = l1
30+
l1 = l1.next
31+
else:
32+
l.next = l2
33+
l2 = l2.next
34+
l = l.next
35+
36+
return head
37+
38+
a = ListNode(1)
39+
b = ListNode(2)
40+
c = ListNode(4)
41+
a.next = b
42+
b.next = c
43+
44+
d = ListNode(3)
45+
e = ListNode(5)
46+
d.next = e
47+
48+
l = mergeTwoLists(a, d)
49+
assert l.val == 1
50+
assert l.next.val == 2
51+
assert l.next.next.val == 3
52+
assert l.next.next.next.val == 4
53+
assert l.next.next.next.next.val == 5

0 commit comments

Comments
 (0)
Please sign in to comment.