当我将x插入程序时,如何显示堆栈。如何显示堆栈C
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int Data;
struct Node* next;
} * top;
void popStack()
{
struct Node *temp, *var = top;
if (var == top)
{
top = top->next;
free(var);
}
else
printf("\nStack Empty");
}
void push(int value)
{
struct Node* temp;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->Data = value;
if (top == NULL)
{
top = temp;
top->next = NULL;
}
else
{
temp->next = top;
top = temp;
}
}
void display()
{
struct Node* var = top;
if (var != NULL)
{
printf("\nElements are as:\n");
while (var != NULL)
{
printf("\t%d\n", var->Data);
var = var->next;
}
printf("\n");
}
else
printf("\nStack is Empty");
}
int main(int argc, char* argv[])
{
printf(" Wellcome to Basic Stacking. \n");
top = NULL;
while (1)
{
当我插入的“x”我想程序显示栈和退出,但之后我在这个节目中插入X将是无限循环并且不显示堆栈,不要退出它不起作用我该怎么办????。
char x ;
int value;
if (value != x)
{
printf("please enter Your Name:");
scanf("%d", &value);
push(value);
fflush(stdin);
display();
}
else
{
// popStack();
display();
break;
}
}
getch();
}
与您的问题无关,但在C规范中明确提到只使用输入流(如stdin)调用'fflush'为* undefined behavior *。一些图书馆将它作为扩展来实现,但你应该避免这样做。 –
与您的问题更相关的可能是您在初始化之前使用'value',因此具有* indeterminate *值。也请花一些时间阅读[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –