0

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;
}

3 Answers 3

1

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;  
   } 
Sign up to request clarification or add additional context in comments.

1 Comment

Answering as per requirement.. ;)
1

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");

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.