写作业时遇见的,但由于蒟蒻看不太懂大佬们的代码,所以根据数组的快排写了这个
还是直接丢代码吧()
#include<stdio.h>
#include<algorithm>
using namespace std;
struct Node
{
struct Node* next;
struct Node* last;
int a;
};
struct Node head;
void Nodeswap(struct Node* a, struct Node* b) //交换节点
{
struct Node* temp;
//交换父节点
temp = a->last;
a->last = b->last;
b->last = temp;
temp->next = b;
a->last->next = a;
//交换子节点
temp = a->next;
a->next = b->next;
b->next = temp;
if (temp != NULL)//其中有末尾节点的特判
temp->last = b;
else b->next = NULL;
a->next->last = a;
return;
}
int Nodelength()//链表长度
{
int i = 0;
struct Node* temp = head.next;
while (temp->next != NULL)
{
i++;
temp = temp->next;
}
i++;
return i;
}
struct Node* Nodelocation(int a)//实现链表的任意访问
{
int i = 1;
struct Node* temp = head.next;
while (i != a)
{
i++;
temp = temp->next;
}
return temp;
}
void listqsort(int l, int r)//链表二分快排 (数组形式)
{
int temp = Nodelocation((int)(l + r) / 2)->a;
int i = l, j = r;
if (i >= j) return;
while (i <= j)
{
while ((Nodelocation(j)->a) > temp)
{
j -= 1;
}
while ((Nodelocation(i)->a) < temp)
{
i += 1;
}
if (i <= j)
{
Nodeswap(Nodelocation(j), Nodelocation(i));
j--; i++;
}
}
if (j > l) listqsort(l, j);
if (i < r) listqsort(i, r);
return;
}
int main()
{
head.next = NULL;
head.a = -1;
struct Node* a = (struct Node*)malloc(sizeof(struct Node));
struct Node* b = (struct Node*)malloc(sizeof(struct Node));
struct Node* c = (struct Node*)malloc(sizeof(struct Node));
struct Node* d = (struct Node*)malloc(sizeof(struct Node));
struct Node* e = (struct Node*)malloc(sizeof(struct Node));
struct Node* f = (struct Node*)malloc(sizeof(struct Node));
struct Node* g = (struct Node*)malloc(sizeof(struct Node));
head.next = a;
struct Node* temp = &head;
a->last = &head; a->next = b; a->a = 20;
b->last = a; b->next = c; b->a = 10;
c->last = b; c->next = d; c->a = 1;
d->last = c; d->next = e; d->a = 15;
e->last = d; e->next = f; e->a = 16;
f->last = e; f->next = g; f->a = 8;
g->last = f; g->next = NULL; g->a = 3;
while (temp->next != NULL)
{
printf("%d ", temp->a);
temp = temp->next;
}
printf("%d ", temp->a);
printf("\n");
listqsort(1, Nodelength());
temp = &head;
while (temp->next != NULL)
{
printf("%d ", temp->a);
temp = temp->next;
}
printf("%d ", temp->a);
return 0;
}
运行如下,是升序
![](https://img-blog.csdnimg.cn/img_convert/b08ed9eaadc563294e8c865feb90baa8.png)