Cover image for Interview Classic 150 Questions P86 Partition List

Interview Classic 150 Questions P86 Partition List


Timeline

Timeline

2025-11-21

init

Linked List

Problem:

The meaning is to put those greater than k in front, and those less than k in the back, but the relative order among the group greater than k remains unchanged, and the relative order among the group less than k also remains unchanged.

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
struct ListNode {
int val;
ListNode *next;
ListNode()
: val(0)
, next(nullptr)
{
}
ListNode(int x)
: val(x)
, next(nullptr)
{
}
ListNode(int x, ListNode *next)
: val(x)
, next(next)
{
}
};

class Solution {
public:
ListNode *partition(ListNode *head, int x)
{
ListNode *virt_node = new ListNode;
virt_node->next = head;

ListNode *prev = virt_node, *p, *tmp;
while (prev->next != nullptr && prev->next->val < x) {
prev = prev->next; //Find the predecessor node of the first node greater than or equal to x
}

if (prev->next == nullptr) { //all vals < x
return head;
}
p = prev;

while (p->next != nullptr) {
if (p->next->val < x) {
tmp = p->next;
p->next = tmp->next;
tmp->next = prev->next;
prev->next = tmp;
prev = tmp;
} else {
p = p->next;
}
}
head = virt_node->next;
delete virt_node;
return head;
}
};