用C语言实现完整的堆栈
我被要求做一个堆栈实现。我需要完成以下功能用C语言实现完整的堆栈,c,struct,stack,C,Struct,Stack,我被要求做一个堆栈实现。我需要完成以下功能 推 流行音乐 满了 空空如也 偷看 显示整个阵列 这是我写的 #include <stdio.h> #include <stdlib.h> #define SIZE 5 /* Stack Structure */ struct stack { int s[SIZE]; int top; }st; int main() { int option; printf("+--------------------
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
/* Stack Structure */
struct stack
{
int s[SIZE];
int top;
}st;
int main()
{
int option;
printf("+-------------------------------------+\n");
printf("1.Push\n2.Pop\n3.Check whether the stack is full\n4.Check whether the stack is empty\n5.Check the Top Element\n6.Display the Stack\n7.Exit\n");
printf("+-------------------------------------+\n");
printf("Enter Choice:\t");
scanf("%d", &option);
while(option == -99)
{
switch(option)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
isFull();
break;
case 4:
isEmpty();
break;
case 5:
peek();
break;
case 6:
display();
break;
case 7:
printf("You Exited from the program");
break;
}
}
return 0;
}
/*Function to add an element to the stack*/
void push ()
{
int num;
if (st.top == (SIZE - 1))
{
printf ("Stack is Full\n");
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
st.top ++;
st.s[st.top] = num;
}
}
/*Function to delete an element to the stack*/
int pop()
{
int num;
if (st.top == -1)
{
printf ("Stack is Empty\n");
return st.top;
}
else
{
num = st.s[st.top];
printf ("Popped element is = %d", st.s[st.top]);
st.top --;
}
return (num);
}
/*Function to Check whether the stack is full*/
void isFull()
{
if(st.top == SIZE - 1)
printf("Stack is Full");
else
printf("Stack has %d elements", st.top - 1);
}
/*Function to Check whether the stack is Empty*/
void isEmpty()
{
if(st.top == -1)
printf("Stack is Empty");
else
printf("Stack has %d elements", st.top - 1);
}
/* Function to display the top element*/
void peek()
{
printf("Top most element: \t%d", st.s[st.top]);
}
/* Function to display the stack*/
void display ()
{
int i;
if (st.top == -1)
{
printf ("Stack is empty\n");
}
else
{
printf ("\n The status of the stack is \n");
for (i = st.top; i >= 0; i--)
{
printf ("%d\n", st.s[i]);
}
}
printf ("\n");
}
我真的需要把它做完。这是我的任务之一。请帮助我,非常感谢您的时间。:-) 您退出是因为您正在输入一个介于1和7之间的选项,但您的while循环正在检查-99。因此跳过while循环,然后退出 我猜你实际上想做的是不断提示用户进行操作,直到他们退出。试着考虑一下你真正想要在程序中循环的功能 另外,不要害怕在代码中放入print语句,并逐行跟踪流程。这将对调试有很大帮助
祝你在这次任务中好运 当然,当您选择数字时,进程停止工作。当变量option等于-99时,程序会工作,这永远不会发生,因为您的选择总是在数字1-7之间
当您期望条件
while(option==-99)
为真时,可以通过编写option>=1&&option来解决此问题。如果您更改while(option=-99)
->while(option!=7)
,而(option=-99)当此条件为真时,会发生什么情况?为什么是-99?最好在while(1)中加一个switch case,并在其中写入breakWarning,因为在main之前没有原型化/声明函数。我建议使用调试器调试程序。尝试解决错误。这将实现你任务的目标。
+-------------------------------------+
1.Push
2.Pop
3.Check whether the stack is full
4.Check whether the stack is empty
5.Check the Top Element
6.Display the Stack
7.Exit
+-------------------------------------+
Enter Choice: 1
Process returned 0 (0x0) execution time : 6.304 s
Press any key to continue.