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
会产生3
与top->prev->data
和top->data
相同的结果。
有人可以解释原因吗?
答案 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