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++)
1 class Solution { 2 public: 3 ListNode* partition(ListNode* head, int x) { 4 ListNode* dummy=new ListNode(-1); 5 dummy->next=head; 6 ListNode* pre=dummy,* cur=head; 7 while(pre->next&&pre->next->val<x) 8 pre=pre->next; 9 cur=pre; 10 while(cur->next){ 11 if(cur->next->val<x){ 12 ListNode* t=cur->next; 13 cur->next=t->next; 14 t->next=pre->next; 15 pre->next=t; 16 pre=t; 17 } 18 else 19 cur=cur->next; 20 } 21 return dummy->next; 22 } 23 };