问题描述
您好,我正在尝试使用链接列表创建一个动态队列来创建它的节点,但是我在插入方法方面遇到了一些问题,我传递给函数的数据在某一时刻会丢失并返回垃圾。
主要问题在于Nodo * PushQ(Nodo * nodo,int val)
代码
Hello, I'm trying to make a dynamic queue using linked list to create the nodes of it, but I have some problems with the method of insertion, at one point the data that I pass to the function looses and it returns trash.
The main problem is in Nodo* PushQ(Nodo *nodo, int val)
The code
#include <iostream>
using namespace std;
// Create new node
struct Nodo{
int val;
Nodo *next;
};
class Queue
{
public:
Nodo *nodo, *end, *front; // [front]->[node]->[end]->NULL
Queue() // Constructor
{
nodo = end = front = NULL;
}
Nodo* PushQ(Nodo *nodo, int val) // Insert value
{
if(nodo == NULL) // At this point is all right, but next, it looses the data and pass to val trash
{
nodo = new Nodo;
nodo->val = val; // At this point the data is gone, now it shows trash
front = nodo; // front end
front->next = NULL; // [data|*next]->[data|*next]->NULL
end = front;
}
else
{
nodo = front->next;
front = nodo;
front->next = NULL;
}
return nodo;
}
int PopQ(Nodo *nodo) // Show queue data
{
int aux = 0;
nodo = new Nodo;
nodo = end;
while(nodo) // Infinite loop
{
cout << nodo->val << endl;
aux = nodo->val;
}
return aux;
}
};
int main()
{
Queue *Q1 = new Queue;
Q1->nodo = Q1->PushQ(Q1->nodo, 5);
Q1->nodo = Q1->PushQ(Q1->nodo, 20);
Q1->nodo = Q1->PushQ(Q1->nodo, 6);
Q1->nodo = Q1->PushQ(Q1->nodo, 7);
Q1->nodo = Q1->PushQ(Q1->nodo, 33);
Q1->PopQ(Q1->nodo);
return 0;
}
我的尝试:
使用Visual Studio 2015进行一些调试,但我不明白为什么垃圾出现
What I have tried:
Some debugging with Visual Studio 2015, but I don't understand why the trash appears
推荐答案
val = nodo->val; // At this point the data is gone, now it shows trash
with
nodo->val = val;
它应解决数据消失的问题。
这种语法非常奇怪。
it should solve the data gone problem.
This syntax is really weird.
Q1->nodo = Q1->PushQ(Q1->nodo, 5);
否则,推送
确实是错误的,完整的分析和重写是有序的。整个程序很混乱。
您应该考虑一下您的需求:队列,链接列表或链接列表队列。
Otherwise, push
is really buggy, a completed analyze and rewrite is in order. The whole program is confuse.
You should think about what you want: a queue, a linked list or a queue of linked lists.
使用Visual Studio 2015进行一些调试
Some debugging with Visual Studio 2015
你应该真的学会使用调试器。
这篇关于需要一些链接列表队列的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!