2012-08-10 68 views
0

请帮助下面的段。当n从堆栈的顶部移除,堆栈是空的,输出应该是“-1弹出的”。(我越来越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; 
} 

回答

0

我认为这符合你的意图更好:

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

爱德和匿名正确地指出,你可以明确地打印-1修复原来的错误。然而,首先让你的逻辑不那么脆弱(并且偶然修复这个特定的bug)对我来说似乎是一个更大的胜利。

1

逻辑错误,你是比较反对零和希望的输出-1!

if (top == NULL) { 
     printf("%d popped\n", top);  
    return; 
    } 

应该

if (top == NULL) { 
     printf("%d popped\n",-1);  
    return; 
    } 
+0

为什么使用'printf'格式访问一个常量? – 2012-08-10 10:26:54

+0

按照要求应答..;) – perilbrain 2012-08-10 10:29:46

1

因为NULL是空指针(即指向任何内容),通常具有0

值就改线

printf("%d popped\n", top); 

printf("-1 popped\n");