C 堆栈实现-链表
我试图弄清楚为什么我的堆栈结构没有弹出元素,并且认为堆栈为NULL(我从两次执行的pop()中得到else条件)?我很困惑,因为printf显示元素正在添加到堆栈中C 堆栈实现-链表,c,linked-list,stack,C,Linked List,Stack,我试图弄清楚为什么我的堆栈结构没有弹出元素,并且认为堆栈为NULL(我从两次执行的pop()中得到else条件)?我很困惑,因为printf显示元素正在添加到堆栈中 #include <stdio.h> #include <stdlib.h> typedef struct node { int element; struct node *pnext; } node_t; void push(node_t *stack, int elem
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int element;
struct node *pnext;
} node_t;
void push(node_t *stack, int elem){
node_t *new = (node_t*) malloc(sizeof(node_t)); // allocate pointer to new node memory
if (new == NULL) perror("Out of memory");
new->pnext = stack;
new->element = elem;
stack = new; // moves the stack back to the top
printf("%d\n", stack->element);
}
int pop(node_t *stack) {
if (stack != NULL) {
node_t *pelem = stack;
int elem = stack->element;
stack = pelem->pnext; // move the stack down
free(pelem); // free the pointer to the popped element memory
return elem;
}
else {
printf("fail");
return 0; // or some other special value
}
}
int main(int argc, char *argv[]){
node_t *stack = NULL ; // start stack as null
push(stack, 3);
push(stack, 5);
int p1 = pop(stack);
int p2 = pop(stack);
printf("Popped elements: %d %d\n", p1, p2);
return 0 ;
}
#包括
#包括
类型定义结构节点{
int元素;
结构节点*pnext;
}节点t;
无效推送(节点*堆栈,内部元素){
node_t*new=(node_t*)malloc(sizeof(node_t));//分配指向新节点内存的指针
if(new==NULL)perror(“内存不足”);
新建->pnext=堆栈;
新建->元素=元素;
stack=new;//将堆栈移回顶部
printf(“%d\n”,堆栈->元素);
}
int pop(节点*堆栈){
如果(堆栈!=NULL){
node_t*pelem=堆栈;
int elem=堆栈->元素;
stack=pelem->pnext;//向下移动堆栈
free(pelem);//释放指向弹出元素内存的指针
返回元素;
}
否则{
printf(“失败”);
返回0;//或其他一些特殊值
}
}
int main(int argc,char*argv[]){
node_t*stack=NULL;//将堆栈启动为NULL
推(堆栈,3);
推(堆栈,5);
int p1=pop(堆栈);
int p2=pop(堆栈);
printf(“弹出的元素:%d%d\n”,p1,p2);
返回0;
}
正如您在退出push/pop时的一句话中所说,main中的变量堆栈没有改变,所以这就像您什么都没做一样,只是push中出现了内存泄漏
要在推送后将新堆栈置于main中,该函数可以返回新堆栈,但对于已经返回poped值的pop来说,这是不可能的,因此要对两者使用相同的解决方案,只需将参数中变量的地址提供给函数,以允许修改它,因此使用双指针而不是简单的
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int element;
struct node *pnext;
} node_t;
void push(node_t ** stack, int elem){
node_t *new = (node_t*) malloc(sizeof(node_t)); // allocate pointer to new node memory
if (new == NULL) {
perror("Out of memory");
exit(-1);
}
new->pnext = *stack;
new->element = elem;
*stack = new; // moves the stack back to the top
printf("%d\n", (*stack)->element);
}
int pop(node_t ** stack) {
if (*stack != NULL) {
node_t *pelem = *stack;
int elem = (*stack)->element;
*stack = pelem->pnext; // move the stack down
free(pelem); // free the pointer to the popped element memory
return elem;
}
else {
printf("fail");
return 0; // or some other special value
}
}
int main(int argc, char *argv[]){
node_t *stack = NULL ; // start stack as null
push(&stack, 3);
push(&stack, 5);
int p1 = pop(&stack);
int p2 = pop(&stack);
printf("Popped elements: %d %d\n", p1, p2);
return 0 ;
}
这回答了你的问题吗?看看main()堆栈“”已初始化为空。在那之后,它的价值不会改变,也不会改变。
% gcc -Wall s.c
% ./a.out
3
5
Popped elements: 5 3