-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.08---qsortSingleLinkedlist.cpp
98 lines (93 loc) · 1.96 KB
/
7.08---qsortSingleLinkedlist.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
node* makelist(int d[],int n)
{
node *head = new node();
head->data = 0;
node *pre = head,*cur = head;
for(int i=0;i<n;i++)
{
cur = new node();
cur->data = d[i];
pre->next = cur;
pre = cur;
}
pre->next = NULL;
return head;
}
struct node *partition(struct node *head, struct node *end,
struct node **newHead, struct node **newEnd)
{
struct node *pivot = end;
struct node *prev = NULL, *cur = head, *tail = pivot;
while(cur != pivot)
{
if(cur->data < pivot->data)
{
if((*newHead) == NULL)
(*newHead) = cur;
prev = cur;
cur = cur->next;
}
else
{
if(prev)
prev->next = cur->next;
struct node *tmp = cur->next;
cur->next = NULL;
tail->next = cur;
tail = cur;
cur = tmp;
}
}
if((*newHead) == NULL)
(*newHead) = pivot;
(*newEnd) = tail;
return pivot;
}
struct node *quickSortRecur(struct node *head, struct node *end)
{
if(!head || head == end)
return head;
node *newHead = NULL, *newEnd = NULL;
struct node *pivot = partition(head, end, &newHead, &newEnd);
if(newHead != pivot)
{
struct node *tmp = newHead;
while(tmp->next != pivot)
tmp = tmp->next;
tmp->next = NULL;
newHead = quickSortRecur(newHead, tmp);
tmp = getTail(newHead);
tmp->next = pivot;
}
pivot->next = quickSortRecur(pivot->next, newEnd);
returnn ewHead;
}
void quickSort(struct node **headRef)
{
(*headRef) = quickSortRecur(*headRef, getTail(*headRef));
return;
}
int main()
{
int d[]={2,5,8,4,7,9,3,1};
node *head = makelist(d,8),*end;
node *pre;
end = head;
while(end->next != NULL)
end = end->next;
pre = head->next;
quickSort(&head);
while(pre != NULL)
{
cout << pre->data << " ";
pre = pre->next;
}
return 0;
}