[LeetCode] 86. Partition List 解题思路

时间:2022-05-31 15:57:02

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 两部分,首先想到的是用两个指针从两段向中间扫来求解。但是题目是列表,不能从后往前扫,并且移动后的相对位置要保存和之前一致,则不能用这种方法。

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

     ListNode* partition(ListNode* head, int x) {

         if (head == NULL){
return NULL;
} vector<ListNode*> arr; ListNode* tmp = head;
while (tmp != NULL) { if (tmp->val < x) {
arr.push_back(tmp);
} tmp = tmp->next;
} tmp = head;
while (tmp != NULL) { if (x <= tmp->val) {
arr.push_back(tmp);
} tmp = tmp->next;
} for (int i = ; i < arr.size()-; i++) {
arr[i]->next = arr[i+];
}
arr[arr.size()-]->next = NULL; head = arr[]; return head; }