黑马程序员技术交流社区

标题: 用java代码编写堆栈,回顾一些基础知识 [打印本页]

作者: 唐溪永    时间: 2012-2-21 10:11
标题: 用java代码编写堆栈,回顾一些基础知识
  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. }
复制代码

作者: 刘基军    时间: 2012-2-21 10:40
顶一个,{:soso_e100:}
作者: 花开~的季节    时间: 2012-2-21 17:50
编写堆栈用集合框架里面的LinkList更简洁,
作者: admin    时间: 2012-2-22 11:24
觉得有帮助的童鞋顶一个!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2