gpt4 book ai didi

c - 堆栈不会在 C 中存储值

转载 作者:行者123 更新时间:2023-11-30 19:32:05 25 4
gpt4 key购买 nike

我目前正在尝试制作一个简单的堆栈菜单程序,它将推送和弹出用户输入的值。 (并打印出堆栈。)

这是我到目前为止的代码。当我尝试插入一个值(情况1)时,我认为它有效 - 但我不确定,因为当我尝试打印堆栈(情况3)时,它总是说“堆栈是空的!”。当我尝试弹出堆栈(情况 2)时,它就崩溃了。

我不知道我的某个结构是否关闭,或者我的指针是否不正确。

感谢您提前提供的帮助,对于困惑的代码我深表歉意 - 我对此还很陌生!

#include<stdio.h> 
#include<stdlib.h>
#define EMPTY 0

struct node
{
int data;
struct node *link;
};
typedef struct node Stack;

Stack* get_node()
{
Stack *tmp;
tmp = (Stack*) malloc(sizeof(Stack));
tmp->link = EMPTY;
return tmp;
}

void push(Stack **top, int data)
{
Stack *tmp;
tmp = *top;

*top = get_node();

(*top)->data = data;
(*top)->link = tmp;
}

void pop(Stack **top)
{
Stack *tmp;
int num;
if (top == EMPTY)
{
printf("Stack is Empty!");
}
else
{
tmp = *top;
printf("%d", tmp->data);
*top = tmp->link;
free(tmp);
}
}

void stack(Stack *top)
{
if (top == EMPTY)
{
printf("Stack is Empty...");
}
else
{
Stack *tmp = top;
while (tmp->link != EMPTY)
{
printf("%d", tmp->data);
tmp = tmp->link;
}
}
}

void menu(int choice)
{
Stack *top = EMPTY;
int data;

switch (choice)
{
case 1:
printf("Enter Data : ");
scanf_s("%d", &data);
push(&top, data);
break;

case 2:
pop(&top);
break;

case 3:
stack(top);
break;

case 4:
exit(1);
}
}

void main()
{
int choice;

printf("< < = M e n u = = >\n");
printf("1.push\n");
printf("2.pop\n");
printf("3.print_all\n");
printf("4.quit\n");
printf("Select : ");
while (1)
{
scanf_s("%d", &choice);
menu(choice);
}
}

最佳答案

做一些小的改变,比如在 menu() 函数中将 top pointer 作为 static ,因为如果你不会将其设置为 static ,它每次都会用 zero 进行初始化。替换这个

Stack *top = EMPTY;

  static Stack *top ;

并修改stack()函数,您将少打印一个元素

void stack(Stack *top)
{
if (top == EMPTY)
{
printf("Stack is Empty...");
}
else
{
Stack *tmp = top;
while (tmp != EMPTY) // here you wrote as tmp->link
{
printf("%d \n ", tmp->data);
tmp = tmp->link;
}
}
}

剩下的所有逻辑都是正确的。我希望它有帮助。

关于c - 堆栈不会在 C 中存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490171/

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