这是我的 C 程序,用于实现堆栈(以节点作为链表)。我正在创建一个新堆栈,返回指针,然后使用指针和我想要分配的数据调用 rpn_stack_push() 函数。
但显然堆栈的顶部节点始终为 NULL,即使我在 rpn_stack_push() 函数中更新它。
为什么会发生这种情况?有没有办法在不更改函数定义的情况下修复它?
struct _rpn_stack{
int data;
struct _rpn_stack *link;
};
typedef struct _rpn_stack rpn_stack_t;
rpn_stack_t* rpn_stack_new() {
rpn_stack_t *top;
top = NULL;
return top;
}
void rpn_stack_push(rpn_stack_t *s, void *data) {
rpn_stack_t* temp = malloc(sizeof(rpn_stack_t));
temp->data = (int) *((int*) data);
temp->link = s;
s = temp;
}
int main()
{
rpn_stack_t* n;
n = rpn_stack_new();
int a = 12;
int c = 13;
int* d = &c;
int* b = &a;
rpn_stack_push(n, d);
rpn_stack_push(n, b);
while (n != NULL)
{
printf("%d -> ", n->data);
n = n->link;
}
return 0;
}
正常情况下应该打印 13->12->,但它根本不会进入循环,因为栈顶节点 (n) 为 NULL!
最佳答案
void rpn_stack_push(rpn_stack_t *s, void *data)
与 rpn_stack_t *s 一起使用意味着您使用了按值参数调用,调用该函数后,s 指针不会改变其值。
因此,请将函数 rpn_stack_push
的原型(prototype)从 void rpn_stack_push(rpn_stack_t *s, void *data)
更改为 void rpn_stack_push(rpn_stack_t **s, void *data)
如下:
void rpn_stack_push(rpn_stack_t **s, void *data) {
rpn_stack_t* temp = (rpn_stack_t*)malloc(sizeof(rpn_stack_t));
temp->data = (int) *((int*)data);
temp->link = *s;
*s = temp;
}
调用时请替换以下行:
rpn_stack_push(n, d);
rpn_stack_push(n, b);
由
rpn_stack_push(&n, d);
rpn_stack_push(&n, b);
那么它应该可以工作。
关于c - 使用节点实现堆栈,函数外部不知道顶部节点指针,顶部指针始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54753177/