【发布时间】:2018-07-14 11:29:17
【问题描述】:
我想在一个链表中排序,在不弄乱地址的情况下更改节点之间的值,当我设置交换条件时,我不能在那里放置任何代码。我尝试插入 printf 并更改值(除了交换)并导致错误。
我想知道我的代码中哪个部分有问题,以及如何在不对结构进行太多更改的情况下解决此问题,此代码是根据我所学的知识进行实验的,感谢 Advance 伙计们
#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;
}
【问题讨论】:
-
或者,@H.S,假设语言标签是错误的。您不能“混合”C 和 C++ 代码;它是 C 或 C++。而且它似乎编译了 Occam's Razor 说它是具有 C 编码风格的 C++。
-
“你不能混合”——至少不能在同一个编译单元中......
-
“导致错误” - 哪种错误?
-
@Aconcagua 后期显示不显示nad返回值过百万
-
我不知道它的哪一部分是 C++,但我确实尝试将 = new Nodes() 更改为 malloc() 但仍然不起作用...关于我应该更改的任何建议?
标签: c++ sorting linked-list