首页 > 编程语言 > 详细

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

时间:2019-10-06 13:25:26      阅读:99      评论:0      收藏:0      [点我收藏+]

一  数组实现的队列

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

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

 

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

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

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