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.

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.

链接地址: http://www.djcxy.com/p/79868.html

上一篇: 使用javascript对堆栈元素进行排序

下一篇: 如何显示动态堆栈和队列中的所有元素(c ++)