【问题标题】:stack implementation - linked list栈实现——链表
【发布时间】: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 ;
}

【问题讨论】:

标签: c linked-list stack


【解决方案1】:

正如你退出时所说的那样, 除了 push

中的内存泄漏

要在 push 之后将新堆栈放在 main 中,该函数可以返回新堆栈,但这对于 pop 已经返回弹出值是不可能的,所以要两者都有相同的解决方案,只需将参数中的变量地址提供给函数以允许修改它,所以是双指针而不是简单的

#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

【讨论】: