This is the program.
#include<iostream>
#include<string>
using namespace std;
struct stack
{
int inf;
stack* link;
} *start, *p;
void push(stack*, stack*, int);
void pop(stack*, stack*);
int main()
{
int s = 0;
string thing;
cin >> thing;
while (thing != "end")
{
if (thing == "push")
{
push(start, p, s);
}
if (thing == "pop")
{
pop(start, p);
}
cin >> thing;
}
return 0;
}
void push(stack *start, stack *p, int s)
{
cin >> s;
p = start;
start = new stack;
start->inf = s;
start->link = p;
cout << "pushed " << start->inf << endl;
}
void pop(stack *start, stack *p)
{
cout << "popped " << start->inf;
p = start;
start = start->link;
delete p;
}
It's a simple program to allow me to push and pop items to and from a stack, but for some reason the pop()
just won't work. If I add an if(start)
before the pop
it just skips it, making me think that the stack somehow becomes NULL after push
is completed. Basically everything works until it reaches the cout << "popped " << start->inf;
line, when it just crashes (no error message) which again makes me think the stack becomes null before it reaches pop()
. Any suggestions?
First, both of your function's signature are weird:
Assuming
start
points to top of stack, you should discardp
. It should be a local variable to the function, not a parameter.Second, let's see
push
implementation:this one looks ALMOST good. What you missed is that
start
is declared as a pointer to stack, and you are changing the pointer inside the function, which is a value parameter instead of a reference. With your current signature, you can change whatstart
POINTS TO, but notstart
itself. You can either declare it as pointer to pointer to stack, and change the body accordingly (you need double dereference for assigninginf
andlink
) or use reference parameter by adding&
before the parameter name. The same case applies to yourpop
function.