C 堆栈实现输出
请帮助完成下面的部分。当n从堆栈顶部移除且堆栈为空时,输出应为'-1 popped'。(我得到的是0 atm)C 堆栈实现输出,c,C,请帮助完成下面的部分。当n从堆栈顶部移除且堆栈为空时,输出应为'-1 popped'。(我得到的是0 atm) 逻辑故障,您正在与零进行比较,并且希望输出为-1 if (top == NULL) { printf("%d popped\n", top); return; } 应该是 if (top == NULL) { printf("%d popped\n",-1); return; }
逻辑故障,您正在与零进行比较,并且希望输出为-1
if (top == NULL) {
printf("%d popped\n", top);
return;
}
应该是
if (top == NULL) {
printf("%d popped\n",-1);
return;
}
因为NULL是NULL指针(即指向nothing的指针),通常值为0 换线就行了
printf("%d popped\n", top);
到
我认为这更符合你的意图:
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;
}
正如Ed和Anon正确指出的那样,您可以通过显式打印
-1
来修复原始错误。然而,首先让您的逻辑不那么脆弱(顺便说一句,修复了这个特定的错误)对我来说似乎是一个更大的胜利。按照要求回答。)
printf("-1 popped\n");
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;
}