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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//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.
Last edited on
In an actual stack memory you would only be able to view the top, but since that isn't the case you don't need to pop all of them for displaying and push them back in after, it's just pointless.

And the reason it doesn't work is because you (in PushPtr function) assign top=newP; and newP is a local variable.

Note: top=newP; shouldn't be inside the ifelse statement because you do it either way...
Topic archived. No new replies allowed.