Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R than or equal to x.
You should preserve the original relative order of the nodes in each of the.
For example,
Given 1->4->3->2->5->2
and x = 3,
Return 1->2->2->4->3->5
.
Issue: Given a list and integer x, move all elements in the list that are less than x to the front of an element that is greater than or equal to X. Requires that the elements of the interior of the second part of the move are in the same relative position as the original.
When you see the topic, you need to divide a column number into two parts less than X and greater than or equal to X, the first thought is to use two pointers from the two paragraphs to the middle sweep to solve. However, the topic is a list, cannot be swept forward from the back, and the relative position after the move to save and before the same, you cannot use this method.
The second idea is to store the new list order in an array, and then establish a pointer relationship between the elements in the array. This idea is relatively simple, also submitted through.
1listnode* partition (listnode* head,intx) {2 3 if(Head = =NULL) {4 returnNULL;5 }6 7Vector<listnode*>arr;8 9listnode* tmp =head;Ten while(TMP! =NULL) { One A if(Tmp->val <x) { - Arr.push_back (TMP); - } the -TMP = tmp->Next; - } - +TMP =head; - while(TMP! =NULL) { + A if(x <= tmp->val) { at Arr.push_back (TMP); - } - -TMP = tmp->Next; - } - in for(inti =0; I < arr.size ()-1; i++) { -Arr[i]->next = arr[i+1]; to } +Arr[arr.size ()-1]->next =NULL; - theHead = arr[0]; * $ returnhead;Panax Notoginseng -}
[Leetcode] 86. Partition List Problem Solving ideas