86. 分隔链表
方法
/**
* 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:
// 维护两个链表small和large,small是比x元素小的组成的,large是比x元素大的组成的
ListNode* partition(ListNode* head, int x) {
// small是比x元素小的组成的
ListNode* small = new ListNode(-1);
ListNode* smallCur = small;
// large是比x元素大的组成的
ListNode* large = new ListNode(-1);
ListNode* largeCur = large;
// 遍历原链表
ListNode* cur = head;
while(cur){
// 比x小的就链接到small链上,注意是创建一个新的节点new ListNode(cur->val);而不是把直接链接到原来head链表的节点上
if(cur->val < x){
smallCur->next = new ListNode(cur->val);
smallCur = smallCur->next;
}
else{ // 比x大的就链接到large链上
largeCur->next = new ListNode(cur->val);
largeCur = largeCur->next;
}
cur = cur->next;
}
// 拼接
smallCur->next = large->next;
return small->next;
}
};