链表快排
今天看到一个华为笔试题的链表快排,很有兴趣就写了一下,发现其实其中的细节还是很多的,值得记录一下。
思路:
主要思想是:{1、选取一个标记结点,在链表里为了省时间就直接取第一个元素作为标记结点;2、遍历这段链表,用一个small指针来维护所有小于当前结点的元素的最后的位置,也就是小于标记结点和大于标记结点的分界点;3、如果当前的值小于标记结点的值那么就和small指针交换,small指针后移,这样就能在线性时间内找到分界点;4、接下来就递归处理标记点的左边和右边。}
代码:
#include <iostream> using namespace std; struct Node { int val; Node* next; Node(){}; Node(int val){ this->val=val; this->next=NULL; }; }; void insert(Node** cur,int val){ (*cur)->next=new Node(val); (*cur)=(*cur)->next; } void quick(Node* LH,Node* L,Node* R){ if(L==NULL||L==R||(R!=NULL&&R->next==L)||R==LH){ return ; } Node* small=L; Node* cur=L->next; Node* last=LH; while(cur!=R){ if(cur->val<L->val){ last=small; small=small->next; int t=cur->val; cur->val=small->val; small->val=t; } cur=cur->next; } int t=small->val; small->val=L->val; L->val=t; quick(LH,L,last); quick(small,small->next,R); } void out(Node* H){ Node* cur=H; while(cur){ cout<<cur->val<<" "; cur=cur->next; } cout<<endl; } int main(){ Node* alist=new Node(3); Node* H = new Node();//构建空结点 H->next=alist; insert(&alist,5); insert(&alist,10); insert(&alist,9); out(H->next); quick(H,H->next,NULL); out(H->next); }

浙公网安备 33010602011771号