gpt4 book ai didi

c++ - 通过修改链接对链表进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:14 25 4
gpt4 key购买 nike

我正在尝试通过修改链接而不是交换数据来对链接列表进行排序。我正在使用选择排序。我不知道我哪里出错了。我是初学者,请帮助我。

struct node
{
int data;
node* link;
};

node* p;

void sort()
{
node* temp = p;
node* save;
node* prev;
node* tprev;
node* push = new node;

tprev = NULL;
for (; temp != NULL; temp = temp->link)
{
push = temp->link;
for (; push != NULL; push = push->link)
{
if (push->data<temp->data)
{
save->link = temp->link;
temp->link = push->link;
push->link = save->link;
prev->link = temp;
tprev->link = push;
}

prev = push;
}

tprev = temp;
}
}

最佳答案

void sort(){
node *temp, *push;
node *tprev, *pprev;
node *save;

tprev = NULL;
for (temp = p; temp != NULL; temp = temp->link){
pprev = temp;
for (push=temp->link; push != NULL; push = push->link){
if (push->data < temp->data){
save = temp->link;
temp->link = push->link;
if(save == push)
push->link = temp;
else
push->link = save;
if(pprev != temp)
pprev->link = temp;
if(tprev)
tprev->link = push;
else
p = push;
save = temp;
temp = push;
push = save;
}
pprev = push;
}
tprev = temp;
}
}

关于c++ - 通过修改链接对链表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com