gpt4 book ai didi

c - 使用链表实现堆栈的意外结果

转载 作者:行者123 更新时间:2023-11-30 21:09:18 29 4
gpt4 key购买 nike

我正在编写这个程序,我想了解为什么我得到错误的打印(应该是 1,2,3,4,5)而是给出一些地址。我的 stackIsEmpty() 甚至没有按照预期的方式工作,即在堆栈为空时停止打印值。这是我的代码:

#include <stdlib.h>
#include <stdio.h>

//Stacks using Structures and linked list and pointerws.

typedef struct Stack{
//Type of the elements of the stack. Here integers
int elem;
//To of the stack
struct Stack* previous;
} Stack;

void initialize(Stack *st);
void push(Stack *st, int element);
int pop(Stack *st);
int stackIsEmpty(Stack *st);

int main(){
int i;
Stack st;
Stack *pt_st = &st;
initialize(pt_st);

//Test phase...
for(i=0; i<5; i++)
push(pt_st, i+1);

for(i=0; i<5; i++)
printf("here is one element: %d\n", pop(pt_st));
//End of test with error!
return 0;
}

void initialize(Stack *st){
st = NULL;
}

void push(Stack *st, int element){
Stack *sta = (Stack*)malloc(sizeof(Stack));
if (sta != NULL)
{
sta->previous = st;
sta->elem = element;
st = sta;
free(sta);
}
else
exit(0);
}

int pop(Stack *st){
if(!stackIsEmpty(st))
{
printf("stack is empty cannot pop\n");
return 0;
}
else
{
int number = st->elem;
Stack* copy = st->previous;
free(st);
st = copy;
return number;
}
}

int stackIsEmpty(Stack *st){
if(st == NULL)
return 0;
else
return 1;
}

最佳答案

您创建的堆栈指针pt_st通过值传递给函数,因此函数仅修改它的本地副本。

您可以创建一个指向指针的指针,或将 pt_st 设置为全局变量。

您的 push 函数也有问题。

我修改了你的代码,使 pt_st 成为全局的,所以它现在可以工作了:

#include <stdlib.h>
#include <stdio.h>

//Stacks using Structures and linked list and pointerws.

typedef struct Stack{
//Type of the elements of the stack. Here integers
int elem;
//To of the stack
struct Stack* previous;
} Stack;

void initialize();
void push(int element);
int pop();
int stackIsEmpty();

Stack *pt_st; // made pt_st global, so functions can modify it

int main(){
int i;
initialize();

//Test phase...
for(i=0; i<5; i++)
push(i+1);

for(i=0; i<5; i++)
printf("here is one element: %d\n", pop(pt_st));
//End of test with error!
return 0;
}

void initialize(){
pt_st = NULL; // set it to NULL
}

void push(int element){
Stack *sta = malloc(sizeof(Stack)); // don't need to cast malloc
sta->elem = element;

sta->previous = pt_st; // set sta's previous

pt_st = sta; // point to the pushed node
}

int pop(){
if(stackIsEmpty())
{
printf("pt_stack is empty cannot pop\n");
return 0;
}
else
{
int number = pt_st->elem;
Stack *temp = pt_st; // create a temp copy of the first node's address
pt_st = pt_st->previous;
free(temp);
return number;
}
}

int stackIsEmpty(){
if(pt_st == NULL)
return 1; // if pt_st is NULL, then the stack is empty
else
return 0;
}

关于c - 使用链表实现堆栈的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852450/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com