[英]How to show all elements in dynamic stack and queue (c++)
i need to show all elements of a stack and queue, using static structures i used a recursive function, but with dynamic it doesnt works well at all. 我需要显示堆栈和队列的所有元素,使用静态结构我使用了递归函数,但是对于动态它根本无法很好地工作。
When i use the functions, it shows the elements correctly, but after that, whatever i do, the program crashes. 当我使用这些功能时,它会正确显示元素,但是此后,无论我做什么,程序都会崩溃。
Also, in order to do the print(), a requeriment is that it suppose that i can only have acces to the top, so if i show the top, i cant see the previous node, unless i pop the current top, then show the new top. 另外,为了执行print(),一个要求是假设我只能访问顶部,因此,如果我显示顶部,除非看到当前顶部,否则我将看不到前一个节点,然后显示新的顶部。
This is the code for the dynamic stack: 这是动态堆栈的代码:
class Person{
public:
string nombre,weight;
Person *sig;
public:
void Capture();
void Show();
};
typedef Person *pPerson;
class stack{
public:
pPerson top;
void Push();
void PushPtr(pPerson object);
void Pop();
pPerson Top();
void Print();
};
//Push new elements
void stack::Push(){
pPerson newP;
newP=new Person();
newP->Capture();
if(top==NULL){
newP->next=NULL;
top=newP;
}
else{
newP->next=top;
top=newP;
}
size++;
}
//For print
void Stack::Print(){
if(Empty()){
return;
}
pPerson x=Top();
Pop();
Print();
PushPtr(x);
}
//Function to recieve the "x" pointer
void Stack::PushPtr(pPerson object){
pPerson newP;
newP=object;
if(size==0){
newP->next=NULL;
top=newP;
}
else{
newP->next=top;
top=newP;
}
size++;
}
As i said, the queue is doing the same thing, but figuring out whats the problem here, im pretty sure i'll fix the queue :-/ 就像我说的那样,队列正在做同样的事情,但是要弄清楚这里出了什么问题,我很确定我会解决队列:-/
Thanks in advance. 提前致谢。
Stack walks are usually done this way: 堆栈遍历通常通过以下方式完成:
void Stack::Print(){
pPerson cur = top;
while (cur != nullptr) {
cur->printIt(); // other print function.
cur = cur->next;
}
}
Unless there is some existential reason to pop the stack and push it back on. 除非有某种存在的原因要弹出堆栈并将其推回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.