HOME/剑指Offer/

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

Article Outline
TOC
Collection Outline

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

  • 要求:只能使用长度为 X 的固定长度数组实现同样长度的队列和栈,超过则报错;
  • 队列的结构为先进先出,栈是先进后出;
  • 数组实现栈
package cn.test;

/**
 * @Author smallmartial
 * @Date 2020/3/2
 * @Email [email protected]
 */
public class ArrayToStack {

    private Integer[] arr;
    //指当前栈的位置
    private Integer index;

    public ArrayToStack(Integer initSize) {
        if (initSize < 0) {
            throw new IllegalArgumentException("数据参数不正确");
        }
        arr = new Integer[initSize];
        index = 0;
    }

    public void push(Integer obj) {
        if (index == arr.length) {
            throw new ArrayIndexOutOfBoundsException("the stack is full");
        }
        arr[index++] = obj;
    }

    public Integer pop() {
        if (index == 0) {
            throw new ArrayIndexOutOfBoundsException("the stack is empty");
        }
        return arr[--index];
    }

    public Integer peek() {
        if (index == 0) {
            return null;
        }
        return arr[index - 1];
    }

    public static void main(String[] args) {
        ArrayToStack arrayToStack = new ArrayToStack(2);
        arrayToStack.push(1);
        arrayToStack.push(2);
        System.out.println(arrayToStack.pop());
        System.out.println(arrayToStack.pop());
    }
}
  • 数组实现队列
package cn.test;

/**
 * @Author smallmartial
 * @Date 2020/3/2
 * @Email [email protected]
 */
public class ArrayToQueue {
    private Integer[] arr;
    private Integer size;
    private Integer start;
    private Integer end;

    public ArrayToQueue(Integer initSize) {
        if (initSize < 0) {
            throw new IllegalArgumentException("数据参数不正确");
        }
        arr = new Integer[initSize];
        size = 0;
        start = 0;
        end = 0;
    }

    public void push(Integer obj) {
        if (size == arr.length) {
            throw new ArrayIndexOutOfBoundsException("the stack is full");
        }
        size++;
        arr[end] = obj;
        end = (end == arr.length - 1) ? 0 : end + 1;
    }

    public Integer poll() {
        if (size == 0) {
            throw new ArrayIndexOutOfBoundsException("the stack is full");
        }
        size--;
        Integer temp = start;
        start = (start == arr.length - 1) ? 0 : start + 1;
        return arr[temp];
    }

    public Integer peek() {
        if (size == 0) {
            return null;
        }
        return arr[start];
    }

    public static void main(String[] args) {
        ArrayToQueue arrayToQueue = new ArrayToQueue(3);
        arrayToQueue.push(1);
        arrayToQueue.push(2);
        arrayToQueue.push(3);
        System.out.println(arrayToQueue.poll());
        System.out.println(arrayToQueue.poll());
        System.out.println(arrayToQueue.poll());
    }
}