简繁EN

LeetCodeNo. 124

[LeetCode with Python] 86. Partition List

Contents

Problem

Problem page: https://leetcode.com/problems/partition-list/
Topics: Linked List, Two Pointers
Difficulty: 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.


Analysis

After the first node greater than or equal to x, I detach each node less than x in turn and insert it after the initial run of nodes less than x. I start by putting a dummy node new_head before the head. That way, if the first node itself has a value greater than or equal to x (say 4->1 with x=3, which gives 1->4), I don't need a special case for the head pointer.
I skip that initial run since those nodes are already in the right place. l_pos stops at the last node in that run. Then I scan the rest of the list, keeping parent one node behind cur.
If I come across a node less than x, I move it just after l_pos. I then set l_pos to the newly inserted node so the next node less than x goes after it. The nodes with values greater than or equal to x stay where they are, so both parts keep their original order. The time complexity is O(n) because I visit each node only a constant number of times. I only change next pointers, and the dummy node is the only node I create, so the extra space is O(1).


Code

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

Article link: https://xnerv.wang/en/leetcode-partition-list/