我试图弄清楚为什么我的堆栈结构没有弹出元素并认为堆栈为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 ;
}
答案 0 :(得分:1)
如前所述,当退出 push / pop 时, main 中的变量 stack 保持不变,因此就像您什么都没做,但 push
中的内存泄漏除外要在函数可以返回新堆栈的 push 之后在主堆栈中添加新堆栈,但这对于 pop 已经返回弹出值的情况是不可能的,因此两者都有相同的解决方案,只是使用将参数in中的变量的地址赋予函数以允许对其进行修改,因此使用双指针而不是简单的
#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");
exit(-1);
}
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 ;
}
编译和执行:
% gcc -Wall s.c
% ./a.out
3
5
Popped elements: 5 3