C에서 스택을 구현하려고하지만 새로운 데이터가 추가 될 때마다 이전 값이 대체됩니다. 여기 내 코드는 다음과 같습니다.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에서 새 노드가 선언 될 때마다 데이터는 스택의 모든 이전 값에서 변경됩니다. 뭔가 무작위로 값을 변경하게하는 포인터에 대해 알지 못하는 무언가가 있습니까?
EDIT :이 새로운 코드 동작 :
#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;
}
코드에 누락 된 'sizeof'을 추가했습니다. – unwind
@unwind, thanks. – hmjd
Ahh, 고마워요. 전에 이것을 한 번 보았지만, 이제 알게되었습니다. – mrobinson7627