原题描述
输入格式
测试样例格式说明:
根据菜单操作:
1、输入1,表示要实现Push操作,紧跟着输入要Push的元素
2、输入2,表示要实现Pop操作
3、输入3,返回栈顶元素
4、输入4,返回栈的元素个数
5、输入5,表示从栈顶到栈底输出栈的所有元素
6、输入0,表示程序结束
输入样例
1
2
1
4
1
6
5
3
4
2
5
2
2
2
0
输出样例
A Stack Has Created.
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Element 2 is Successfully Pushed!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Element 4 is Successfully Pushed!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Element 6 is Successfully Pushed!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Stack is: 6 4 2
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Top Element is 6!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Length of the Stack is 3!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Element 6 is Successfully Poped!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Stack is: 4 2
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Element 4 is Successfully Poped!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
The Element 2 is Successfully Poped!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
Pop Error!
1:Push
2:Pop
3:Get the Top
4:Return the Length of the Stack
5:Load the Stack
0:Exit
Please choose:
题目分析
没什么好说的,开大一点的数组,按题目要求操作即可
代码
#include <iostream>
using namespace std;
int main()
{
int choice,i,e,a[105]= {0},top;
top=1;//说明1是栈底
printf("A Stack Has Created.\n");
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
scanf("%d", &e);
a[top++]=e; //入栈
a[0]++; //长度加一
printf("The Element %d is Successfully Pushed!\n",e);
break;
case 2:
if(top==1)//栈空
printf("Pop Error!\n");
else
{
e=a[--top];//出栈
a[0]--;
printf("The Element %d is Successfully Poped!\n", e);
}
break;
case 3:
if(top==1)
printf("Get Top Error!\n");
else
{
e=a[top-1];//获取栈顶元素
printf("The Top Element is %d!\n", e);
}
break;
case 4:
printf("The Length of the Stack is %d!\n",a[0]);
break;
case 5:
if(top==1)
printf("The Stack is Empty!");
else
{
printf("The Stack is: ");
for(i=top-1; i>=1; i--) //遍历输出栈元素(从栈顶开始)
printf("%d ",a[i]);
}
printf("\n");
break;
case 0:
return 1;
}
}
}
/*
*/