A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 唐溪永 黑马帝   /  2012-2-21 10:11  /  2093 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Stack {

  2.         int[] data;
  3.         int maxSize;
  4.         int top;
  5.         public Stack(int maxSize) {
  6.                 this.maxSize = maxSize;
  7.                 data = new int[maxSize];
  8.                 top = -1;
  9.         }
  10.        
  11.         /**
  12.          * 依次加入数据
  13.          * @param data 要加入的数据
  14.          * @return 添加是否成功
  15.          */
  16.         public boolean push(int data) {
  17.                 if(top+1== maxSize) {
  18.                         System.out.println("栈已满!");
  19.                         return false;
  20.                 }
  21.                 this.data[++top] = data;
  22.                 return true;
  23.         }
  24.        
  25.         /**
  26.          * 从栈中取出数据
  27.          * @return 取出的数据
  28.          */
  29.         public int pop() throws Exception{
  30.                 if(top==-1) {
  31.                         throw new Exception("栈已空!");
  32.                 }
  33.                 return this.data[top--];
  34.         }
  35.        
  36.         public static void main(String[] args) throws Exception {
  37.                 Stack stack=new Stack(1000);
  38.                 stack.push(1);
  39.                 stack.push(2);
  40.                 stack.push(3);
  41.                 stack.push(4);
  42.                 stack.push(5);
  43.                 while(stack.top>=0)
  44.                 {
  45.                         System.out.println(stack.pop());
  46.                 }               
  47.         }
  48. }
复制代码

3 个回复

倒序浏览
顶一个,{:soso_e100:}
回复 使用道具 举报
编写堆栈用集合框架里面的LinkList更简洁,
回复 使用道具 举报
admin 程序媛 2012-2-22 11:24:43
板凳
觉得有帮助的童鞋顶一个!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马