Skip to content

Commit bb8aa0d

Browse files
author
shangchun
committed
leetcode
1 parent 05355b2 commit bb8aa0d

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

reorder.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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 head, a ListNode
8+
# @return nothing
9+
def reorderList(head):
10+
# count
11+
count = 0
12+
node = head
13+
tail = node
14+
while node:
15+
count += 1
16+
tail = node
17+
node = node.next
18+
if count <= 2:
19+
return
20+
21+
# reverse right half
22+
step = 0
23+
pivot = (count - 1) / 2;
24+
behind = head
25+
ahead = behind.next
26+
while ahead:
27+
if step < pivot:
28+
behind = ahead
29+
ahead = ahead.next
30+
else:
31+
node = ahead.next
32+
if step == pivot:
33+
behind.next = None
34+
ahead.next = None
35+
else:
36+
ahead.next = behind
37+
behind = ahead
38+
ahead = node
39+
step += 1
40+
41+
# insert
42+
while head and tail:
43+
nodeHead = head.next
44+
nodeTail = tail.next
45+
head.next = tail
46+
tail.next = nodeHead
47+
head = nodeHead
48+
tail = nodeTail
49+
50+
a = ListNode('a')
51+
b = ListNode('b')
52+
c = ListNode('c')
53+
d = ListNode('d')
54+
a.next = b
55+
b.next = c
56+
c.next = d
57+
reorderList(a)
58+
assert a.next == d
59+
assert b.next == c
60+
assert c.next == None
61+
62+
e = ListNode('e')
63+
f = ListNode('f')
64+
g = ListNode('g')
65+
e.next = f
66+
f.next = g
67+
reorderList(e)
68+
assert e.next == g
69+
assert g.next == f
70+
assert f.next == None

0 commit comments

Comments
 (0)