LintCode Q99 Reorder List in Python

  • Jinhai ZHOU
  • 6 Minutes
  • 2017年1月21日
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
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the sorted linked list,
using constant space complexity.
"""
def reorderList(self, head):
# write your code here
# in-place algorithme
# step 1: find middle
if head is None or head.next is None:
return
runner = head
current = head
while runner and runner.next:
runner = runner.next.next
current = current.next
# step 2: reverse the second half
list2 = self.reverseList(current)
# step 3: interlace the first half and reversed second half
list1 = head
while list2 and list1 != list2:
temp1 = list1.next
list1.next = list2
temp2 = list2.next
if list2 != temp1:
list2.next = temp1
list1 = temp1
list2 = temp2
return head
def reverseList(self, head):
# reverse a linked list
if head is None or head.next is None:
return head
previous = head.next
current = head
current.next = None
while previous:
temp = previous.next
previous.next = current
current = previous
previous = temp
return current
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。