简繁EN

LeetCodeNo. 124

【LeetCode with Python】 86. Partition List

目录

题目

原题页面:https://leetcode.com/problems/partition-list/
题目类型:Linked List, Two Pointers
难度评价:Medium

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.


分析

我的做法是把排在第一个大于等于x的节点后面的小于x的节点逐个摘下来,插到开头那段小于x的节点后面。先在头前面接一个哑节点new_head,这样第一个节点本身就大于等于x时(比如4->1,x=3,输出1->4),不用单独处理头指针。
先跳过开头连续小于x的节点,它们本来就在正确位置,l_pos停在这段的最后一个节点上。再往后扫,parent始终是cur的前一个节点。
往后扫到小于x的节点,就摘下来接在l_pos后面,然后l_pos挪到刚接上的这个节点,下一个小于x的节点就接在它后面;大于等于x的节点原地不动,所以两部分各自的顺序都没变。每个节点只经过常数次,时间是O(n);只改next指针、除了哑节点没新建过节点,所以额外空间是O(1)。


代码

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
class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
if None == head or None == head.next:
return head
new_head = ListNode(-1)
new_head.next = head
tail = head
while None != tail.next:
tail = tail.next
cur = head
parent = new_head
l_pos = new_head

while tail != parent and None != cur:
if cur.val >= x:
break
parent = parent.next
cur = cur.next
l_pos = l_pos.next
parent = parent.next
if None != cur:
cur = cur.next
#l_pos = l_pos.next

while tail != parent and None != cur:
if cur.val < x:
parent.next = cur.next
cur.next = l_pos.next
l_pos.next = cur
l_pos = l_pos.next
cur = parent.next
else:
parent = parent.next
cur = cur.next
return new_head.next

本文地址:https://xnerv.wang/leetcode-partition-list/