簡體   English   中英

堆棧實現——鏈表

[英]stack implementation - linked list

我試圖弄清楚為什么我的堆棧結構沒有彈出元素並認為堆棧為 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 ;
}

正如在退出push/pop時的評論中所說, main 中的變量堆棧沒有變化,所以就像你什么都沒做,除了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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM