Reputation: 33
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;
}
Upvotes: 0
Views: 84
Reputation: 67713
I think this fits your intent better:
void pop(void) {
int n;
if (top == NULL) {
// empty: magic sentinel value
n = -1;
} else {
n = top->item;
// not empty: update the stack
struct node *temp = top;
top = top->prev;
free(temp);
}
printf("%d popped\n", n);
return;
}
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.
Upvotes: 0
Reputation: 59987
Because NULL is the null pointer (i.e a pointer to nothing) and usually has the value of 0.
Just change the line
printf("%d popped\n", top);
to
printf("-1 popped\n");
Upvotes: 1
Reputation: 8187
Logic fault, You are comparing against zero and want an output of -1 !!!
if (top == NULL) {
printf("%d popped\n", top);
return;
}
Should be
if (top == NULL) {
printf("%d popped\n",-1);
return;
}
Upvotes: 1