我正在尝试在 C 中实现一个堆栈,但是每当添加新数据时,旧值都会被覆盖。这是我的代码:
#include <stdlib.h>
struct snode {
int data;
struct snode *prev;
struct snode *next;
};
static struct snode stack;
static struct snode *stackpointer = NULL;
void push(int data) {
if(stackpointer == NULL) {
stack.data = data;
stack.prev = NULL;
stack.next = NULL;
stackpointer = &stack;
return;
}
struct snode newnode;
newnode.data = data;
newnode.prev = stackpointer;
newnode.next = NULL;
stackpointer = &newnode;
}
int pop() {
int retdata = stackpointer->data;
if(stackpointer->prev == NULL) {
stackpointer = NULL;
}
else {
stackpointer = stackpointer->prev;
stackpointer->next = NULL;
}
return retdata;
}
int peek() {
return stackpointer->data;
}
每当在 push 中声明一个新节点时,堆栈的所有先前值中的数据都会更改。有什么我不知道的指针会导致它们随机改变值吗?
编辑:这个新代码有效:
#include <stdlib.h>
struct snode {
int data;
struct snode *prev;
struct snode *next;
};
static struct snode *stackpointer = NULL;
void push(int data) {
struct snode *newnode = (struct snode*)malloc(sizeof(struct snode));
newnode->data = data;
newnode->prev = stackpointer;
newnode->next = NULL;
stackpointer = newnode;
}
int pop() {
int retdata = stackpointer->data;
if(stackpointer->prev != NULL) {
stackpointer = stackpointer->prev;
free(stackpointer->next);
}
else {
free(stackpointer);
stackpointer = NULL;
}
return retdata;
}
int peek() {
return stackpointer->data;
}