[LeetCode] 86. Partition List 解题思路

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

问题:给定一个列表和整数 x,将列表中所有小于 x 的元素移到大于或等于 x 的元素前面。要求,移动后两部分的内部的元素相对位置和原来的保存一致。

一看到题目,需要将一列数分为小于 x 和 大于或等于 x 两部分,首先想到的是用两个指针从两段向中间扫来求解。但是题目是列表,不能从后往前扫,并且移动后的相对位置要保存和之前一致,则不能用这种方法。

第二个思路是用数组存储新的列表顺序,然后在数组中建立 元素间的指针关系。这个思路比较简单,也提交通过了。

 1     ListNode* partition(ListNode* head, int x) {
 2         
 3         if (head == NULL){
 4             return NULL;
 5         }
 6             
 7         vector<ListNode*> arr;
 8         
 9         ListNode* tmp = head;
10         while (tmp != NULL) {
11             
12             if (tmp->val < x) {
13                 arr.push_back(tmp);
14             }
15 
16             tmp = tmp->next;
17         }
18         
19         tmp = head;
20         while (tmp != NULL) {
21             
22             if (x <= tmp->val) {
23                 arr.push_back(tmp);
24             }
25             
26             tmp = tmp->next;
27         }
28             
29         for (int i = 0 ; i < arr.size()-1; i++) {
30             arr[i]->next = arr[i+1];
31         }
32         arr[arr.size()-1]->next = NULL;
33         
34         head = arr[0];
35         
36         return head;
37         
38     }
原文地址:https://www.cnblogs.com/TonyYPZhang/p/5068641.html