我正在尝试为堆栈操作编写一个带有帮助函数的单独文件。我想通过引用将堆栈顶部作为参数传递给主文件中的堆栈操作。
由于 top 正在被修改,我通过引用传递指针 top。但即便如此,它也不起作用。我哪里错了?
PS:我知道这不是实现 Stack 的最佳方式,但我只是想了解它为什么不起作用。
//堆栈.h
void print(stacknode **P)
{
stacknode *S;
S=*P;
printf("Printing stack from top to bottom...\n");
stacknode *temp=S;
while(temp != NULL)
{
printf("%d\t", temp->data);
temp=temp->next;
}
printf("\n");
}
void push(stacknode **P, int n)
{
stacknode *S;
S=*P;
stacknode *new=(stacknode *)malloc(sizeof(stacknode));
new->data=n;
new->next=S;
S=new;
print(&S);
}
//main.c
main()
{
printf("Creating new stack...\n");
stacknode *S=NULL;
printf("Pushing first number....\n");
push(&S, 2);
print(&S);/*Prints nothing*/
}