我试图在队列中插入3个元素,然后提取它们中的每一个。每次提取后,我都会打印剩余的元素。问题是,在最后一个元素,它告诉我,我已经提取了正确的元素,但该元素仍然保留在队列中。
输出如下: 打印:8 1 4
摘录:4 打印:8 1
摘录:1 打印:8
摘录:8 打印:8 ---->这是问题所在。它应该是:“没有元素!”
#include<malloc.h>
#include<stdio.h>
struct Nod{
int id;
Nod* next;
};
Nod* insert(Nod* nod,int id){
Nod* nou = (Nod*)malloc(sizeof(Nod));
nou->id = id;
nou->next = 0;
if (nod == 0)
nod = nou;
else
{
nou->next = nod;
nod = nou;
}
return nod;
}
int extract(Nod* nod){
if (nod->next == 0){
Nod* temp = nod;
nod = 0;
return temp->id;
}
else
{
Nod* temp = nod;
while (temp->next->next)
temp = temp->next;
Nod* aux = temp->next;
temp->next = 0;
return aux->id;
}
}
void print(Nod* nod){
if (nod == 0)
printf("\nNo elements !\n");
else
{
printf("\nPrint : ");
Nod* temp = nod;
while (temp){
printf("%d ",temp->id);
temp = temp->next;
}
printf("\n");
}
}
void main(){
Nod* nod = 0;
///////////
nod = insert(nod, 4);
nod = insert(nod, 1);
nod = insert(nod, 8);
print(nod);
///////////
int r = extract(nod);
printf("\nExtracted : %d",r);
print(nod);
///
int y = extract(nod);
printf("\nExtracted : %d", y);
print(nod);
///
int p = extract(nod);
printf("\nExtracted : %d", p);
print(nod);
}
答案 0 :(得分:0)
int extract(Nod* nod){
if (nod->next == 0){
Nod* temp = nod;
nod = 0;
return temp->id;
}
问题出在上面的代码中。当只剩下一个元素时,你正在制作nod
0
但它没有被反映,因为nod
是按值传递的。你可以传递nod
作为参考。
int extract(Nod* &nod){
答案 1 :(得分:0)
int extract(Nod* *nod){
if (((*nod)->next) == 0){
Nod* temp = *nod;
*nod = 0;
return temp->id;
}
else
{
Nod* temp = *nod;
while (temp->next->next)
temp = temp->next;
Nod* aux = temp->next;
temp->next = 0;
return aux->id;
}
}
这就是我编写代码的方式,它的工作原理! :)谢谢!