當我將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/)。 –