import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* Class StackDemo
* Description 堆栈的基本算法
* Author Chenlly
* Date 08-12-06
* Version 1.0
*/
public class StackDemo{
private static final int MAXSIZE=10;
private int[] intArray;
private int top;
public StackDemo(){
intArray=new int[MAXSIZE];
top=-1;
}
//进栈
public void push(int paraValue){
intArray[++top]=paraValue;
}
//出栈
public int pull(){
return intArray[top--];
}
//查看栈顶元素
public int peek(){
return intArray[top];
}
//查看堆栈是否已空
public boolean isEmpty(){
return top==-1;
}
//从控制台输入数据
//type=1 输入操作序列,type=2输入入队数据
public int putDate(String type){
boolean bflag=false;
int intValue=0; if(type.equals("1")){
System.out.println("请输入操作序列");
}else{
System.out.println("请入栈数据");
}
while(!bflag){
try{
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);
String str=br.readLine();
System.out.println("请输入操作序列");
intValue=Integer.parseInt(str);
bflag=true;
}catch(NumberFormatException ex){
ex.printStackTrace();
System.out.println("输入有误,请重新输入");
}catch (Exception ex){
ex.printStackTrace();
}
}
return intValue;
}
//主调函数
public static void main(String []args){
StackDemo sd=new StackDemo();
System.out.println("请选择");
System.out.println("1:进栈");
System.out.println("2:出栈");
System.out.println("3:查看栈顶元素");
System.out.println("4:查看堆栈是否已空");
System.out.println("5:退出操作");
while(true){
int op=sd.putDate("1");
switch(op){
case 1:
int value=sd.putDate("2");
if(sd.top==MAXSIZE){
System.out.println("堆栈已满,请出栈");
}else{
sd.push(value);
}
break;
case 2:
if(sd.isEmpty()){
System.out.println("堆栈已空,请入栈");
}else{
int data=sd.pull();
System.out.println("出栈的元素为:"+data);
}
break;
case 3:
if(sd.isEmpty()){
System.out.println("堆栈已空,栈里已没有元素");
}else{
int top=sd.peek();
System.out.println("栈顶元素为:"+top);
}
break;
case 4:
if(sd.isEmpty()){
System.out.println("堆栈已空");
}else{
System.out.println("堆栈未空");
}
break;
case 5:
default:
System.exit(1);
}
}
}
}