/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (head == NULL)
return head;
// 创建一个头结点
ListNode* voidptr = new ListNode(-1);
voidptr->next = head;
ListNode* curNode = head;
ListNode* prv_curNode;
ListNode* lastNode = voidptr;
// 先找到一个大于等于x的节点
while(curNode != NULL && curNode->val < x)
curNode = curNode->next, lastNode = lastNode->next;
// 这个节点不存在,就直接返回
if (curNode == NULL)
return head;
// 创建2个节点用来控制链表
prv_curNode = curNode;
curNode = curNode->next;
while(curNode != NULL){
if (curNode->val < x){
prv_curNode->next = curNode->next;
curNode->next = lastNode->next;
lastNode->next = curNode;
lastNode = curNode;
curNode = prv_curNode->next;
}
else{
prv_curNode = curNode;
curNode = curNode->next;
}
}
return voidptr->next;
}
};
static int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
LetCode 86. 分隔链表
最新推荐文章于 2024-05-15 06:55:05 发布