According to the idea of the ordinary fast line, select 1 points as the center point, to ensure that the center point to the left is smaller than the center point, the center point to the right than the center point.
The implementation of a single-linked list is:
1. Make the first node a center point.
2. Create 2 pointers (P,Q), p points to the head node, Q points to the next node of P.
3.Q begins the traversal, if the value of Q is found to be smaller than the value of the center point, then P=p->next, and performs the current p's value and Q's value exchange, Q traverses the end of the chain.
4. The value of the head node is exchanged with the value of P. At this point the P node is the center point, and the 1-wheel quick-row is completed
5. Use recursive method to complete sorting
#include <iostream>#include<time.h>using namespacestd;//defining a linked list nodestruct_tnode{intNvalue; _tnode*Pnext; _tnode () {memset ( This,0,sizeof(_tnode));};//////////////////////////////////////Quick sort of single-linked list///////////////////////////////////voidQuickSort (_tnode* pbegin, _tnode*pEnd) { if(NULL = =Pbegin|| NULL = =pEnd|| Pbegin = =pEnd) { return; } _tnode* Pfirst =Pbegin; _tnode* Psecond = pfirst->Pnext; intNmidvalue = pbegin->Nvalue; //Start Sorting while(Psecond! = Pend->pnext && Psecond! =NULL) { if(Psecond->nvalue <nmidvalue) {Pfirst= pfirst->Pnext; Std::swap (Pfirst->nvalue, psecond->nvalue); } Psecond= psecond->Pnext; } //1-round sequencing after replacement pivotStd::swap (Pbegin->nvalue, pfirst->nvalue); QuickSort (Pbegin, Pfirst); QuickSort (Pfirst-Pnext, pEnd);//The next here is important, otherwise it will cause a dead loop}voidMain () {Srand (static_cast<unsignedint>(Time (NULL))); Const intnnodecnt =Ten; _tnode* Phead =New_tnode (); _tnode* Plastnode =Phead; //construct a linked list for(intncnt =0; ncnt < nnodecnt; ++ncnt) {_tnode* Pnode =New_tnode (); Pnode->nvalue = rand ()%Ten; Plastnode->pnext =Pnode; Plastnode=Pnode; } //to view the output before it is sortedPlastnode =Phead; for(intncnt =0; ncnt < nnodecnt; ++ncnt) {_tnode* Pnode = plastnode->Pnext; Plastnode=Pnode; cout<<pNode->nValue<<Endl; } cout<<Endl; //View Sort OutputQuickSort (Phead, Phead +nnodecnt); Plastnode=Phead; for(intncnt =0; ncnt < nnodecnt; ++ncnt) {_tnode* Pnode = plastnode->Pnext; Plastnode=Pnode; cout<<pNode->nValue<<Endl; } Plastnode=Phead; //Delete 11 nodes that contain a head for(intncnt =0; ncnt <= nnodecnt; ++ncnt) {_tnode* Pnode =Plastnode; Plastnode= pnode->Pnext; DeletePnode; } System ("Pause");}
Results after sorting:
Quick sort of single-linked list