publicclassStack{privateintstack[]=newint[10];privateinttop;privatebooleanisFull(){returntop==10;}privatebooleanisEmpty(){returntop==0;}publicvoidstack(){top=0;for(inti=0...
public class Stack
{private int stack[]=new int[10];
private int top;
private boolean isFull()
{
return top==10;
}
private boolean isEmpty()
{
return top==0;
}
public void stack()
{
top=0;
for(int i=0;i<10;i++)
stack[i]=0;
}
public void push(int a)
{
if(isFull())
System.out.println("stack is full");
else
System.out.println("push("+a+")");
stack[++top]=a;
}
public int pop()
{
if(isEmpty())
{
System.out.println("stack is empty");
return 0;
}
else
{
System.out.println("pop ("+stack[top]+")");
return stack[top--];
}
}
public int getTop()
{
if(isEmpty())
{
System.out.println("stack is empty");
return 0;
}
else
{
System.out.println("Top is ("+stack[top]+") ");
return stack[top-1];
}
}
public static void main(String []args)
{
Stack s=new Stack();
while(true)
{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~This is a Stack~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("其功能如下:");
System.out.println("1. 进栈");
System.out.println("2. 出栈");
System.out.println("3. 取栈顶");
System.out.println("0. 退出系统");
int op; //op=1或2或3或0;输入怎么输入?
switch(op)
{
case 1:
System.out.println("请输入一个整数:");
int n; //输入,怎么输入?
s.push(n);
break;
case 2:
s.pop();
break;
case 3:
s.getTop();
break;
case 0:
return;
default:
System.out.println("Error!");
}
}
}
}
展开