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
有点用到了倒置链表II的方法,将符合要求的结点放置在指向pre指针的后面。这道题的思路应该是找到第一个大于等于x值的结点,他前一个位置始终定位pre指针,放置比x小的结点。
方法一(C++)
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* dummy=new ListNode(-);
dummy->next=head;
ListNode* pre=dummy,* cur=head;
while(pre->next&&pre->next->val<x)
pre=pre->next;
cur=pre;
while(cur->next){
if(cur->next->val<x){
ListNode* t=cur->next;
cur->next=t->next;
t->next=pre->next;
pre->next=t;
pre=t;
}
else
cur=cur->next;
}
return dummy->next;
}
};