【发布时间】:2026-01-10 08:15:02
【问题描述】:
我试图弄清楚为什么我的堆栈结构没有弹出元素并认为堆栈为 NULL(我从 pop() 执行两次获得 else 条件)?我很困惑,因为 printf 显示元素正在添加到堆栈中。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int element;
struct node *pnext;
} node_t;
void push(node_t *stack, int elem){
node_t *new = (node_t*) malloc(sizeof(node_t)); // allocate pointer to new node memory
if (new == NULL) perror("Out of memory");
new->pnext = stack;
new->element = elem;
stack = new; // moves the stack back to the top
printf("%d\n", stack->element);
}
int pop(node_t *stack) {
if (stack != NULL) {
node_t *pelem = stack;
int elem = stack->element;
stack = pelem->pnext; // move the stack down
free(pelem); // free the pointer to the popped element memory
return elem;
}
else {
printf("fail");
return 0; // or some other special value
}
}
int main(int argc, char *argv[]){
node_t *stack = NULL ; // start stack as null
push(stack, 3);
push(stack, 5);
int p1 = pop(stack);
int p2 = pop(stack);
printf("Popped elements: %d %d\n", p1, p2);
return 0 ;
}
【问题讨论】:
-
看看 main()。 'stack' 被初始化为 NULL。之后没有任何改变或可以改变它的价值。
标签: c linked-list stack