Problem:
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
.
Hide TagsLinked List PointersTest instructions: The first step, similar to the quick sort, divides the unordered list into two parts, which are smaller than the target, and not less than the target's back.
Thinking:
(1) Using the idea of fast sequencing, the nodes that are smaller than the target value are moved forward. However, because the fast ordering is not stable, so it does not meet the requirements of the stability of the problem, if the rapid sequencing is necessarily wrong
(2) Then change the quick sort. The fast-sorting two-pointer-walk direction is reversed, which results in a sort of instability. If both pointers walk in ascending direction at the same time, they are stable.
(3) for the subject, in addition to the walk of the double pointer, but also to increase the precursor pointer and the last less than the target value of the rear drive pointer
Code
Transformation Quick Sort:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {Public:listnode *partition (listnode *head, int x) {ListNode *p=null; Left Pointer ListNode *after=null; Point to the first node not less than x ListNode *pre=head; The precursor node of q is ListNode *q=head; Right pointer while (q!=null) {ListNode *tmp=q->next; if (q->val<x) {if (after==null)///From the first node is less than x {if (p ==null) {p=q; Head=p; } else p=p->next; Do not move} else//The first node is greater than x {if (p==null) {p=q; Head=p; p->next=after; if (after->next==q)//p Q Only one node is not less than x pre=after; pre->next=tmp; } else {p->next=q; p=p->next; p->next=after; if (after->next==q)//p Q Only one node is not less than x pre=after; pre->next=tmp; }}}} else {if (after==null) after=q; pre=q; Continuous nodes not less than x} q=tmp; } return head; } };
Leetcode | | 86. Partition List