1. 程式人生 > >086. Partition List

086. Partition List

題目連結:https://leetcode.com/problems/partition-list/description/

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

 

思路:

  • 根據題目所述,要求將連結串列中小於x(< x )的結點放在連結串列的左側,大於等於x(>= x)的結點放置在連結串列的右側;並且要求元素的相對順序保持不變。
  • 最直觀的想法就是遍歷連結串列,將元素中大於等於x(>= x)的結點拎出來,組成一個新的連結串列;當對原始連結串列遍歷完成後,將拎出來的新連結串列插入到處理後的原始連結串列的後面即可。

  注意:上面描述的是將大於等於x(>= x)的結點拎出來,也可將小於x(< x)的結點拎出來,兩者處理過程基本一樣。只是組合成所求連結串列時插入位置不同。

 

編碼如下

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public: 11 ListNode* partition(ListNode* head, int x) { 12 if (head == nullptr) return head; // 連結串列為空,則直接返回 13 14 // 操作原始連結串列的準備工作 15 // 包括建立一個輔助結點指向連結串列的頭結點 16 ListNode *pHead = new ListNode(-1); 17 pHead->next = head; 18 ListNode *pre = pHead; // pre指向遍歷到的結點的前驅結點 19 ListNode *cur = head; // cur指向遍歷到的當前結點(即待處理結點) 20 21 // 建立指向大於等於x(>= x ) 結點的連結串列 22 // 用pNew指標指向該連結串列的頭結點,pNew為輔助結點 23 ListNode *pNew = new ListNode(-1); 24 ListNode *ptrNew = pNew; 25 26 // 對原始連結串列進行遍歷 27 while (cur != nullptr) 28 { 29 if (cur->val >= x) // 將原始連結串列中大於等於x(>= x)的結點分離出來,形成新的連結串列 30 { 31 ListNode *pTemp = cur; 32 pre->next = pTemp->next; 33 cur = cur->next; 34 35 ptrNew->next = pTemp; 36 ptrNew = ptrNew->next; 37 ptrNew->next = nullptr; 38 } 39 else // 對於原始連結串列中小於x(< x)的結點,移動指標指向即可。 40 { 41 pre = cur; 42 cur = cur->next; 43 } 44 } 45 46 // 將兩部分連線起來 47 // 將原始連結串列中小於x(< x)的部分和原始連結串列中大於等於x(>= x)的部分連線起來 48 pre->next = pNew->next; 49 head = pHead->next; 50 51 // 釋放輔助結點記憶體空間 52 delete pHead; 53 delete pNew; 54 55 return head; 56 } 57 };