赞
踩
#include <iostream> using namespace std; typedef struct LNode{ int data; struct LNode *next; }LNode; /* 带头结点的链表有元素如下 [23, 17, 45, 21, 6, 14, 56, 50] 现在要对链表元素进行快速排序 设原始链表的元素顺序和上述的数组的顺序一致; */ void createList(LNode *p, int *R, int n) //生成单链表 { p->next = NULL; LNode *q; for (int i = n - 1; i >= 0; --i) { q = (LNode*)malloc(sizeof(LNode)); q->data = R[i]; q->next = p->next; p->next = q; } } void printList(LNode *p) { if (p == NULL) return; LNode *q = p->next; while (q != NULL) { cout << q->data << endl; q = q->next; } } void quickSort(LNode *first, LNode *end) //first是指向第一个结点的指针 { if (first == NULL || first == end) return; LNode *p1, *p2; //定义俩个辅助指针 /* p1指向左子链的最右端,p1 而p2一直向右移动,如果p2所指值小于基准值,把p1先向右移动一个,然后交换p1和p2的data */ p1 = first; p2 = first->next; while (p2 != end) { if (p2->data < first->data) //小于基准值 { p1 = p1->next; int temp = p2->data; p2->data = p1->data; p1->data = temp; } p2 = p2->next; } //p1成为了左子链的最右的一个结点 //需要交换p1和基准结点的值,交换后满足了基准结点在中间,它的左侧值都比它小 int temp = p1->data; p1->data = first->data; first->data = temp; quickSort(first, p1); quickSort(p1->next, end); } int main() { LNode *head; int R[] = {23, 17, 45, 21, 6, 14, 56, 50}; int n = 8; //构造了一个带头结点的单链表,注意带头结点 createList(head, R, n); cout << "排序前" << endl; printList(head); quickSort(head->next, NULL); cout << "排序后" << endl; printList(head); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。