I'm trying to implement a LIFO stack recursively without using arrays. The program takes in strings and ints as input, and has a few commands -- namely push <int>
pop
empty
top
and quit
.
Everything but pop
works fine for me, and pop
only works partially. It's fine if you're popping just one int, but beyond that it returns me a stack is empty
even though it is not. I understand why this is happening, but I'm not sure how to fix it.
int stack(int top, int last) {
int m = read_symbol();
if (m != READ_FAIL) {
if (m == PUSH_SYMBOL) {
int n = read_int();
top = stack(n, top);
} else if (m == POP_SYMBOL) {
if (top == INT_MIN) {
printf("pop error - stack is empty\n");
top = stack(INT_MIN, INT_MIN);
} else {
top = stack(last, INT_MIN);
}
} else if (m == TOP_SYMBOL) {
if (top == INT_MIN) {
printf("top error - stack is empty\n");
} else {
printf("top - %d\n", top);
}
top = stack(top, last);
} else if (m == EMPTY_SYMBOL) {
if (top == INT_MIN) {
printf("stack is empty\n");
} else {
printf("stack is not empty\n");
}
top = stack(top, last);
} else if (m == QUIT_SYMBOL) {
if (top != INT_MIN) {
printf("quit error - stack is not empty\n");
top = stack(top, last);
} else {
printf("goodbye\n");
}
}
}
return top;
}
The top
variable is recursively returned so everything works fine. But when I do something like
push 1
push 2
push 3
top
pop
top
pop
top
the output returned is
top - 3
top - 2
top error - stack is empty (SHOULD BE 1)
ive tried various different approaches but i havent been able to solve it. In fact I introduced the last
parameter just to try and solve this, the rest of the implementation works fine even without last
but this parameter for now seems to work but only for one pop
command because the next recursion level sets last
to INT_MIN
which is then set to top
if you pop
again, hence the false stack is empty
message
any pointers or help would be appreciated.
EDIT: INT_MIN
refers to the C99 limits.h
INT_MIN
which is -(2^32 - 1)