单链表 快速排序
2011-09-07 17:58
323 查看
通过移动链表指针实现单链表快排:
#include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* InitLinkList(int arr[],int N) { if(N < 1) return NULL; Node *p = new Node,*head = p; p->data = arr[0]; p->next = NULL; for(int i=1; i<N; ++i) { p->next = new Node; p = p->next; p->data = arr[i]; p->next = NULL; } return head; } void print(Node* head) { while (head) { cout<<head->data; head = head->next; if (head) { cout<<"->"; } } cout<<endl; } Node* Partion(Node* front, Node* head, Node* tail) { if (!head) { return NULL; } Node* tempHead = head; Node* prev = head; Node* cur = head->next; while (cur != tail) { if (cur->data < head->data) { Node* temp; prev->next = cur->next; cur->next = tempHead; tempHead = cur; cur = prev->next; }else { prev = prev->next; cur = cur->next; } } if (front) { front->next = tempHead; } return tempHead; } Node* QuickSort(Node* front, Node* head, Node* tail) { if (!head || !head->next || head->next == tail || head == tail) { return head; } Node* tempHead = Partion(front, head, tail); Node* resultHead = QuickSort(front, tempHead, head); QuickSort(head, head->next, tail); return resultHead; } int main() { int Arra[13]={5,20,14,1, 8, 11, 2, 6, 9, 2, 4, 17, 13}; Node* head = InitLinkList(Arra, 13); print(head); head = QuickSort(NULL, head, NULL); print(head); return 0; }