LintCode Q96 Partition List in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月12日
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
"""
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 linked list.
@param x: an integer
@return: a ListNode
"""
def partition(self, head, x):
# write your code here
# Given 1->4->3->2->5->2->null and x = 3,
# return 1->2->2->4->3->5->null.
current = ListNode(None, head)
head = current
while current.next and current.next.val < x:
current = current.next
runner = current
while runner and runner.next:
if runner.next.val < x:
temp = runner.next.next
runner.next.next = current.next
current.next = runner.next
current = current.next
runner.next = temp
else:
runner = runner.next
return head.next
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。