【发布时间】:2018-04-25 08:32:36
【问题描述】:
我被要求做一个堆栈实现。我需要以下功能;
- 推送
- 流行音乐
- 已满
- 是空的
- 偷看
- 显示整个数组
这是我写的。
#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");
}
显示 0 个错误,11 个警告。
但是当我运行程序时,它会在询问选择后结束。
输出:
+-------------------------------------+
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.
我真的需要完成它。这是我的任务之一。请帮助我,非常感谢您抽出宝贵的时间。 :-)
【问题讨论】:
-
您预计
while(option == -99)的条件何时为真? -
如果您更改
while(option == -99)->while(option != 7)会发生什么? -
while(option == -99) 这个条件什么时候成立?为什么-99?最好放置 while(1) 并再保留一个 switch case 并在那个 write break
-
警告,因为您没有在 main 之前原型化/声明函数。
-
我建议,使用调试器并调试您的程序。尝试解决错误。这将实现你的任务目标。