2012-08-10 100 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");