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

一  数组实现的队列

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

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

 

posted @ 2019-10-06 10:46  踏月而来  阅读(384)  评论(0编辑  收藏  举报