Skip to content

Commit 3e5e264

Browse files
add leetcode 143
1 parent c6369b7 commit 3e5e264

File tree

2 files changed

+68
-10
lines changed

2 files changed

+68
-10
lines changed

.idea/workspace.xml

Lines changed: 11 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

leetcode/143. Reorder List.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
3+
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
4+
5+
You must do this in-place without altering the nodes' values.
6+
7+
For example,
8+
Given {1,2,3,4}, reorder it to {1,4,2,3}.
9+
'''
10+
11+
12+
# Definition for singly-linked list.
13+
class ListNode(object):
14+
def __init__(self, x):
15+
self.val = x
16+
self.next = None
17+
18+
class Solution(object):
19+
def reorderList(self, head):
20+
if not head or not head.next:
21+
return
22+
ahead, behind = self.split(head)
23+
behind = self.reverse(behind)
24+
head = self.reConnect(ahead, behind)
25+
# split the linkedlist in middle
26+
def split(self, head):
27+
fast = head
28+
slow = head
29+
while fast and fast.next:
30+
slow = slow.next
31+
fast = fast.next
32+
fast = fast.next
33+
middle = slow.next
34+
slow.next = None
35+
return head, middle
36+
# reverse the behind half linkedlist
37+
def reverse(self, head):
38+
reHead = None
39+
curNode = head
40+
while curNode:
41+
nextNode = curNode.next
42+
curNode.next = reHead
43+
reHead = curNode
44+
curNode = nextNode
45+
return reHead
46+
# merge the two linkedlist to one
47+
def reConnect(self, first, second):
48+
head = first
49+
tail = first
50+
first = first.next
51+
while second:
52+
tail.next = second
53+
tail = tail.next
54+
second = second.next
55+
if first:
56+
first, second = second, first
57+
return head

0 commit comments

Comments
 (0)