添加新元素后,为什么所有元素都在堆栈中被替换?

时间:2014-03-04 12:55:24

标签: c pointers data-structures stack

C中的简单堆栈实现:

struct Stack {
  char* data;
  Stack* prev;
};

void push(char* data, Stack** stack) {
  Stack* node = (Stack*)malloc(sizeof(Stack));
  node->data = data;
  node->prev = *stack;
  *stack = node;
}

int main() {
  Stack* top = NULL;
  push("1", &top);
  push("2", &top);
  push("3", &top);
}

然后top->prev->prev->data会产生3top->prev->datatop->data相同的结果。

有人可以解释原因吗?

1 个答案:

答案 0 :(得分:5)

所以,它似乎工作正常。

#include <stdlib.h>
#include <stdio.h>

struct Stack {
    char* data;
    struct Stack* prev;
};

void push(char *data, struct Stack** stack) {
    struct Stack* node = malloc(sizeof(struct Stack));
    node->data = data;
    node->prev = *stack;
    *stack = node;
}

int main() {
    struct Stack* top = NULL;
    push("1", &top);
    push("2", &top);
    push("3", &top);

    printf("top->data: %s\n", top->data);
    printf("top->prev->data: %s\n", top->prev->data);
    printf("top->prev->prev->data: %s\n", top->prev->prev->data);
}

输出结果为:

top->data: 3
top->prev->data: 2
top->prev->prev->data: 1