1. 程式人生 > >LeetCode 86. Partition List 劃分鏈表

LeetCode 86. Partition List 劃分鏈表

pan part tco 指針 head 鏈表 urn ati origin

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 };

LeetCode 86. Partition List 劃分鏈表