首页 > 编程语言 > 详细

java用数组实现栈

时间:2015-02-14 11:04:22      阅读:335      评论:0      收藏:0      [点我收藏+]

1.1.  栈的数据结构

栈是一种先进后出的数据结果,只能在一端(称为栈顶(top))对数据项进行插入和删除。

1.2.  Java实现

StackTest

package ch04;
 
public class StackTest {
 
    public static void main(String[] args) {
 
       ArrayStack stack = new ArrayStack(10);
       System.out.println("isEmpty: "+stack.isEmpty());
       for(int i = 0;i<10;i++){
           stack.push(i);
       }
       System.out.println("isFull: "+stack.isFull());
      
       while(!stack.isEmpty()){
           System.out.println(stack.pop());
       }
      
    }
 
}
 
class ArrayStack{
    private int[] arrInt;//内置数组
    private int top;//栈顶指针
   
    public ArrayStack(int size){
       this.arrInt = new int[size];
       top = -1;
    }
   
    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty(){
       return -1 == top;
    }
   
    /**
     * 判断栈是否已满
     * @return
     */
    public boolean isFull(){
       return arrInt.length -1 == top;
    }
    /**
     * 向栈顶插入一个元素
     * @param item
     */
    public void push(int item){
       if(isFull()){
           throw new RuntimeException("栈已满");
       }
       arrInt[++top] = item;
    }
   
    /**
     * 从栈顶取出一个元素
     * @return
     */
    public int pop(){
       if(isEmpty()){
           throw new RuntimeException("栈为空");
       }
       return arrInt[top--];
    }
}

 

结果如下:

isEmpty: true

isFull: true

9

8

7

6

5

4

3

2

1

0

 

java用数组实现栈

原文:http://blog.csdn.net/u022812849/article/details/43816143

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!