1. 前言
前文我們剛提及了如何用單向鏈表來模擬棧. 我們還可以用數組來模擬棧.使用棧頂指針top來進行棧頂的操作.
2. 數組模擬棧
(1). 棧接口
public interface stack<E> {//壓棧boolean push(E value);//彈棧, 棧非空返回棧頂元素E pop();//返回棧頂元素, 但不彈棧E peek();//判斷棧是否為空boolean isEmpty();//判斷棧是否已滿boolean isFull();
}
(2). 數組模擬棧
public class ArrayStack<E> implements stack<E>, Iterable<E>{//棧頂指針private int top;//數組模擬棧private E[] stack;public ArrayStack(int capacity) {stack = (E[]) new Object[capacity];}@Overridepublic boolean push(E value) {if(isFull()) {return false;}stack[top++] = value;return true;}@Overridepublic E pop() {if(isEmpty()) {return null;}return stack[--top];}@Overridepublic E peek() {if (isEmpty()) {return null;}return stack[top-1];}@Overridepublic boolean isEmpty() {return top < 0;}@Overridepublic boolean isFull() {return top == stack.length;}@Overridepublic Iterator<E> iterator() {return new Iterator<E>() {@Overridepublic boolean hasNext() {return top > 0;}@Overridepublic E next() {return stack[--top];}};}
}
3. 單元測試
public class ArrayStackTest {@Testpublic void test1() {ArrayStack<Integer> stack = new ArrayStack<>(10);stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);stack.push(6);stack.push(7);for (Integer element : stack) {System.out.print(element + " ");}//7 6 5 4 3 2 1}@Testpublic void test2() {ArrayStack<Integer> stack = new ArrayStack<>(10);stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);stack.push(6);stack.push(7);System.out.println(stack.peek());//7System.out.println(stack.pop());//7System.out.println(stack.peek());//6}
}