1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| package com.lei.payment.java.base.algorithm.list.statck;
import com.lei.payment.java.base.algorithm.exception.AlgorithmException; import com.lei.payment.java.base.algorithm.exception.ErrorCode4Algorithm; import com.lei.payment.java.base.algorithm.list.AbstractList;
public class ArrayStack<T> extends AbstractList<T> { private Object[] stack;
private int DEFAULT_STACK_SIZE = 32;
private int size = 0;
public ArrayStack(int size) { if (size < 1) { throw new AlgorithmException(ErrorCode4Algorithm.INDEX_OUT_OF_RANGE); } this.stack = new Object[size]; this.size = 0; }
public ArrayStack() { new ArrayStack<T>(DEFAULT_STACK_SIZE); }
@Override public T pop() throws AlgorithmException { if (this.isEmpty()) { throw new AlgorithmException(ErrorCode4Algorithm.INDEX_OUT_OF_RANGE); } return (T) stack[this.size--]; }
@Override public void push(T t) throws AlgorithmException { if (stack.length == this.size) { resize(this.stack, this.size + DEFAULT_STACK_SIZE); } this.stack[this.size++] = t; }
@Override public int size() throws AlgorithmException { return this.size; }
@Override public T fist() throws AlgorithmException { if (this.isEmpty()) { throw new AlgorithmException(ErrorCode4Algorithm.INDEX_OUT_OF_RANGE); } return (T) this.stack[this.size - 1]; }
@Override public T last() throws AlgorithmException { if (this.isEmpty()) { throw new AlgorithmException(ErrorCode4Algorithm.INDEX_OUT_OF_RANGE); } return (T) this.stack[0]; }
@Override public boolean isEmpty() throws AlgorithmException { return this.size <= 0; }
private void resize(Object[] oldStack, int newSize) { Object[] newStack = new Object[newSize]; for (int i = 0; i < this.size; i++) { newStack[i] = oldStack[i]; } this.stack = newStack; } }
|