遍历链表将比给定值大或相等的节点移到一个新链表里面,最后新旧链表首尾想接即可。
-
/**
-
* 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(NULL==head) return NULL;
-
ListNode *bigger_head=NULL;
-
ListNode *bigger_curr=NULL;
-
ListNode *curr=head;
-
ListNode *pre=NULL;
-
ListNode *re=head;
-
while(curr)
-
{
-
if(curr->val>=x)
-
{
-
if(curr==re) re=curr->next;
-
if(NULL==bigger_head) bigger_head=curr;
-
if(pre) pre->next=curr->next;
-
if(bigger_curr) bigger_curr->next=curr;
-
bigger_curr=curr;
-
curr=curr->next;
-
continue;
-
}
-
pre=curr;
-
curr=curr->next;
-
}
-
if(bigger_curr) bigger_curr->next=NULL;
-
if(pre)pre->next=bigger_head;
-
return re?re:bigger_head;
-
}
-
};
阅读(197) | 评论(0) | 转发(0) |