分割
- 思路:
- 创建两个链表,small 存放小于 x 的元素,large 放大于或等于 x 的元素;
- 遍历完原链表之后,将 small 链表与 large 链表链接;
/**
* Definition for singly-linked list.
* 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* small = new ListNode(0);
ListNode* sHead = small;
ListNode* large = new ListNode(0);
ListNode* lHead = large;
while (head != nullptr) {
if (head->val < x) {
small->next = head;
small = small->next;
} else {
large->next = head;
large = large->next;
}
head = head->next;
}
// link s -> l
large->next = nullptr;
small->next = lHead->next;
return sHead->next;
}
};