双链表的快排
直接上代码吧: 因为是双链表,所以快排的i指针后移和j指针前移可以实现。故而可按照数组快排的方式实现双链表快排。
关键是注意边界,因为是双链表,切莫越界。
1 # include<stdio.h> 2 3 struct dll{ 4 struct Element* head; 5 int size; 6 }; 7 8 struct Element{ 9 int value; 10 struct Element* p; 11 struct Element* r; 12 }; 13 14 typedef struct Element Element; 15 typedef struct dll dll; 16 17 void add(dll* m, int k){ 18 Element* ptr; 19 Element* head; 20 head = (int *)malloc(10 * sizeof(int)); 21 ptr = (int *)malloc(10 * sizeof(int)); 22 ptr->value = k; 23 head = m->head; 24 ptr->r = head; 25 ptr->p = head->p; 26 ptr->p->r = ptr; 27 ptr->r->p = ptr; 28 (m->size) = (m->size) + 1; 29 30 } 31 void init(dll* m, int k){ 32 33 34 Element* ptr; 35 Element* head; 36 head = (int *)malloc(10 * sizeof(int)); 37 ptr = (int *)malloc(10 * sizeof(int)); 38 ptr->value = k; 39 m->head = ptr; 40 ptr->r = ptr; 41 ptr->p = ptr; 42 m->size = m->size + 1; 43 } 44 45 Element* qsort(Element* f, Element* l){ 46 Element* i = f; 47 Element* s = f; 48 Element* j = l; 49 int tmp = i->value; 50 while (i != j){ 51 while ((i != j) && (j->value) >= tmp) 52 { 53 j = j->p; 54 } 55 i->value = j->value; 56 while ((i != j) && ((i->value) <= tmp)) 57 { 58 i = (*i).r; 59 } 60 j->value = i->value; 61 } 62 i->value = tmp; 63 return i; 64 } 65 66 void quicksort(struct Element* i, struct Element* j) 67 { 68 if (i != j) 69 { 70 Element* m = i; 71 Element* n = j; 72 Element* middlep; 73 Element* middler; 74 Element* middle = qsort(m, n); 75 if (middle != i) //关键部分:因为是双链表,所以不可middle不可是两端,否则越界出现死循环。 76 { 77 middlep = middle->p; 78 quicksort(i, middlep); 79 } 80 if (middle != j) //关键部分:因为是双链表,所以不可middle不可是两端,否则越界出现死循环。 81 { 82 middler = middle->r; 83 quicksort(middler, j); 84 } 85 } 86 else 87 return; 88 89 } 90 91 92 void main(){ 93 94 95 dll* t; 96 t = (int *)malloc(20 * sizeof(int)); 97 t->size = 0; 98 init(t, 30); 99 add(t, 6); 100 add(t, 2); 101 add(t, 5); 102 add(t, 56); 103 add(t, 36); 104 add(t, 9); 105 add(t, 98); 106 Element* s = t->head; 107 quicksort(t->head, (t->head)->p); 108 for (int i = 0; i<(t->size); i++){ 109 printf("%d\n", s->value); 110 s = s->r; 111 } 112 system("pause"); 113 114 }