[英]How to show all elements in dynamic stack and queue (c++)
我需要顯示堆棧和隊列的所有元素,使用靜態結構我使用了遞歸函數,但是對於動態它根本無法很好地工作。
當我使用這些功能時,它會正確顯示元素,但是此后,無論我做什么,程序都會崩潰。
另外,為了執行print(),一個要求是假設我只能訪問頂部,因此,如果我顯示頂部,除非看到當前頂部,否則我將看不到前一個節點,然后顯示新的頂部。
這是動態堆棧的代碼:
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++;
}
就像我說的那樣,隊列正在做同樣的事情,但是要弄清楚這里出了什么問題,我很確定我會解決隊列:-/
提前致謝。
堆棧遍歷通常通過以下方式完成:
void Stack::Print(){
pPerson cur = top;
while (cur != nullptr) {
cur->printIt(); // other print function.
cur = cur->next;
}
}
除非有某種存在的原因要彈出堆棧並將其推回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.