Please help with the segment below. When n is removed from the top of the stack and stack is empty, output should be ‘-1 popped’.(I’m getting 0 atm)
void pop(void) {
struct node *temp;
int n;
if (top == NULL) {
printf("%d popped\n", top);
return;
}
n = top->item;
temp = top;
top = top->prev;
free(temp);
printf("%d popped\n", n);
return;
}
I think this fits your intent better:
As Ed and Anon correctly point out, you can fix the original bug by explicitly printing
-1. However, making your logic less fragile in the first place (and incidentally fixing this specific bug) seems like a bigger win to me.