86. Partition List**
https://leetcode.com/problems/partition-list/
题目描述
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
C++ 实现 1
使用 smaller
来链接小于 x
的节点, 用 larger
来链接大于/等于 x
的节点. 注意最后:
q->next = nullptr; // 防止指针指向混乱的问题
p->next = larger->next; // 小于 x 的节点在前面
下面是完整代码:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (!head) return nullptr;
ListNode *smaller = new ListNode(0), *larger = new ListNode(0);
auto p = smaller, q = larger;
while (head) {
if (head->val < x) {
p->next = head;
p = p->next;
} else {
q->next = head;
q = q->next;
}
head = head->next;
}
q->next = nullptr;
p->next = larger->next;
return smaller->next;
}
};