堆栈-基本算法

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);
   }
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值