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
.
Ideas:
1. Because the original relative position cannot be changed, the direct displacement value is not possible.
2. In fact, the problem is similar to the fast ordering of the partition function, the idea is to randomly select a value from the array as a reference value, so that the array is smaller than the reference value of the number in the left side of the reference value, the array is larger than the reference value of the number in the right side of the reference value.
Traversing all nodes and discovering that a node smaller than x is "switched", the process of swapping deletes that node first and then inserts it into the corresponding location.
Here is a premise, even if the first number is less than x, it is not necessary to "exchange."
Another point to note is that after deleting a node in the list, the value of the pointer p may appear undefined, so before deleting, let P point to the next node to delete the node.
classSolution { Public: //Delete a node in the list that is located in Loc, starting with 1 intDelete (listnode* &head,intLoc) {ListNode* p=NULL; ListNode* q=NULL; P=Head; intI=1; //find the precursor node while(i<loc-1&&p->next) { ++i; P=p->Next; } q=p->Next; P->next=q->Next; intVal=q->Val; Free (q); returnVal; } ListNode* Insert (listnode* &head,intLocintval) {ListNode* p=Head; P=Head; intI=1; if(loc==1) {ListNode* s= (listnode*) malloc (sizeof(ListNode)); S->val=Val; S->next=p; returns; } //find the precursor node while(i<loc-1&&p->next) { ++i; P=p->Next; } ListNode* s= (listnode*) malloc (sizeof(ListNode)); S->val=Val; S->next=p->Next; P->next=s; returnHead; } ListNode*partition (ListNode *head,intx) {if(Head==null)returnNULL; intInsertloc=0; intLoc=0; ListNode* p=Head; while(p!=NULL) { ++Loc; if(p->val<x) {++Insertloc; if(insertloc!=Loc) {P=p->Next; intVal=Delete (Head,loc); Head=Insert (Head,insertloc,val); Continue; }} P=p->Next; } returnHead; } };
Partition list (insert and delete of linked list, find precursor node)