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

stack 栈

package com.ljs.day2;

public class ArrayStack {
    private Integer [] arr;
    private Integer size; // size 代表stack中有多少个元素。 有效元素范围[0,size).
    
    public ArrayStack(int length){
        
        if (length <= 0 ) {
            throw new IllegalArgumentException("size less than 0 ");
        }
        
        arr = new Integer[length];
        size = 0;
    }
    
    public void push(int obj){
        if (size == arr.length) {
            throw new IndexOutOfBoundsException("the stack is full");
        }
        arr[size++] = obj; 
    }
    
    public int pop(){
        if (size <= 0) {
            throw new IndexOutOfBoundsException("stack is empty");
        }
        return arr[--size];
    }
    
    public Integer peek() {
        if (size == 0) {
            return null;
        }
        return arr[size-1];
        
    }
    
    
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(3);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }

}

queue 队列

package com.ljs.day2;



public class ArrayQueue {
    
    private Integer[] arr;
    private Integer size;   // 有效元素的size
    private Integer start;  // 有效元素的开端位置    [start,end) 队列中的元素。
    private Integer end;  // 
    
    public ArrayQueue(int length) {
        
        if( length < 0 ){
            throw new IllegalArgumentException("length less than 0");
        }
        arr = new Integer[length];
        size = start = end = 0;
    }
    
    public void add(int num) {
        if (size == arr.length) {
            throw new IndexOutOfBoundsException("run of size");
        }
        size++;
        arr[end] = num;
        end = end == arr.length-1 ? 0:end+1;
    }
    
    public int poll() {
        
        if (size == 0) {
            throw new IndexOutOfBoundsException("queue is empty");
        }
        size--;
        int tmp = start;
        start = start == arr.length-1 ? 0:start+1;
        return arr[tmp];
        
    }
    
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        
        queue.add(1);
        queue.add(2);
        queue.add(3);
        
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        
    }
    
}
原文地址:https://www.cnblogs.com/lijins/p/10155407.html