c++ - 交换链表中的值
问题描述
我想在一个链表中排序,在不弄乱地址的情况下更改节点之间的值,当我设置交换条件时,我不能在那里放任何代码。我尝试插入 printf 并更改值(除了交换)并导致错误。
我想知道我的代码的哪个部分有问题以及如何在不对结构进行太多更改的情况下解决此问题,此代码是根据我所学的知识进行实验的,谢谢提前
#include <stdio.h>
#include <stdlib.h>
typedef struct Nodes
{
int value;
Nodes* next,*prev;
Nodes(int val)
{
value = val;
next = prev = NULL;
}
}Nodes;
Nodes *head,*tail,*curr;
void display()
{
curr = head;
while(curr)
{
printf("%d ",curr->value);
curr=curr->next;
}
}
void swap(Nodes *a,Nodes *b)
{
int temp = a->value;
a->value = b->value;
b->value = temp;
}
void sort()
{
curr = head;
while(curr)
{
Nodes *next = curr->next;
if(curr->value > next->value && next != NULL)
{
// this space cant code anything or it will break
// swap(curr,next);
}
curr = next;
}
}
void insert(int val)
{
if(!head)
{
head = tail = new Nodes(val);
}
else
{
curr = new Nodes(val);
tail->next = curr;
curr->prev = tail;
tail = curr;
}
}
int main()
{
insert(8);
insert(3);
insert(20);
display();
puts("");
sort();
display();
return 0;
}
解决方案
if(curr->value > next->value && next != NULL)
// ^^^^^^^^^^^^ too late!
a && b
首先检查 a 并且仅当 a 为真时才对 b 进行评估——因此仅在已经访问过next
之后nullptr
才评估存在的检查(如果有的话,程序很可能在 if is之前崩溃)。所以反过来检查:*next
next
nullptr
if(next && curr->value > next->value)
那么你的排序算法是不完整的,看起来很像冒泡排序,但只有一个“冒泡”上升......
推荐阅读
- connectivity - 问:在 SAP Cloud SDK 弹性中使用断路器
- matrix - 尝试对两个产品求和时出错,其中一个产品是 1x2 矩阵
- directory - 通用目录(例如不是用户特定的)
- java - 如何使用两个不同的包进行排序?
- c++ - 对 std::variant 中保存的类型调用 << 运算符?
- javascript - 如何检测页面滚动到长 div 的底部?
- javascript - 导航栏中的链接将我重定向到错误的路径
- reactjs - 为什么传递状态值会传递字典?
- java - 如何从两个 DayOfWeeks 之间获取 DayOfWeek 列表
- r - DEoptim 包 - 缺少参数,没有默认值