码迷,mamicode.com
首页 > 编程语言 > 详细

利用数组实现固定大小的队列和栈

时间:2019-10-06 11:12:53      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:exce   poll   except   pac   构造函数   als   obj   font   row   

一  数组实现的队列

     这里的队列大小通过构造函数传递

public class ArrayToQueue {

    Integer[] arr;
    int start;
    int end;
    int size;

    public ArrayToQueue(int capacity) {
        super();
        arr = new Integer[capacity];
    }

    public void push(int obj) {
        if (size == arr.length) {
            throw new IllegalArgumentException();
        }
        size++;
        
        arr[end] = obj;
        // 两种方法都可以
        // end = end == arr.length -1 ? 0 : end +1 ;
        end = (end + 1) % arr.length;
    }

    public int poll() {
        if (size == 0) {
            throw new IllegalArgumentException();
        }
        size--;
        int res = arr[start];
        start = (start + 1) % arr.length;
        return res;
    }

}

 

二  数组实现栈

   栈的大小通过构造函数传递

public class ArrayToStack {

    Integer []  arr ;
    int index;
    
    public ArrayToStack(int initialSize) {
        super();
        arr = new Integer[initialSize];
    }
    
    public void push(int obj) {
        if (index == arr.length) {
            throw new ArrayIndexOutOfBoundsException("The queue is full");
        }
        arr[index++] = obj;
    }

    public Integer pop() {
        if(index == 0) {
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        return arr[--index];
    }
    
    public Integer peek() {
        if(index == 0) {
            return null;
        }
        return arr[index-1];
    }
    
}

 

利用数组实现固定大小的队列和栈

标签:exce   poll   except   pac   构造函数   als   obj   font   row   

原文地址:https://www.cnblogs.com/moris5013/p/11626698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!