首先定義 IStackjava
package cn.com.example.stack; /** * Created by Jack on 2017/3/8. */ public interface IStack<T> { //元素出棧,並返回出棧元素 public T pop() throws IllegalAccessException; //元素入棧 public void push(T element); //獲取棧頂元素 public T peek() throws IllegalAccessException; //判斷棧是否爲空 public boolean isEmpty(); // 棧大小 public int size(); public void clear(); }
接着定義 MyStack 實現 IStack接口 並測試ide
package cn.com.example.stack; import java.util.Arrays; /** * Created by Jack on 2017/3/8. */ public class MyStack<T> implements IStack { private final int DEFAULT_SIZE = 3; private int size = 0; private int capacity = 0; //top指向下一個可以添加元素的位置 private int top = 0; private Object[] array; public MyStack() { this.capacity = this.DEFAULT_SIZE; this.array = new Object[this.capacity]; this.size = 0; } public MyStack(int capacity) { this.capacity = capacity; this.array = new Object[this.capacity]; this.size = 0; } /** * 元素出棧,並返回出棧元素 * * @return */ @Override public Object pop() throws IllegalAccessException { if (this.size == 0) throw new IllegalAccessException("stack element empty"); T element = (T) this.array[top - 1]; this.array[top - 1] = null; this.size--; this.top--; return element; } /** * 元素入棧 * * @param element */ @Override public void push(Object element) { if (this.size < this.capacity) { this.array[this.top] = element; this.top++; this.size++; } else { // 擴容 enlarge(); push(element); } } private void enlarge() { this.capacity = this.capacity + this.DEFAULT_SIZE; Object[] newArray = new Object[this.capacity]; System.arraycopy(array, 0, newArray, 0, array.length); Arrays.fill(array, null); this.array = newArray; } /** * 獲取棧頂元素 * * @return */ @Override public Object peek() throws IllegalAccessException { if (this.size == 0) throw new IllegalAccessException("stack element empty"); return this.array[this.top - 1]; } /** * 判斷棧是否爲空 * * @return */ @Override public boolean isEmpty() { return size == 0; } /** * 獲取棧大小 * * @return */ @Override public int size() { return size; } /** * 清空 棧 */ @Override public void clear() { Arrays.fill(array, null); this.capacity = this.DEFAULT_SIZE; this.array = new Object[this.capacity]; this.size = 0; this.top = 0; } } class MyStackTest { public static void main(String[] args) throws IllegalAccessException { MyStack<String> stack = new MyStack<String>(); stack.push("1"); // 棧頭 System.out.println(stack.peek()); // 棧頭出棧 System.out.println(stack.pop()); // 是否爲空 System.out.println(stack.isEmpty()); System.out.println(stack.size()); for (int i = 1; i <= 10; i++) { stack.push("" + i); } System.out.println(stack.size()); for (int i = 0; i < 10; i++) { String s = (String) stack.pop(); System.out.println(s); } // 清空 //stack.clear(); System.out.println("size = " + stack.size()); } }
輸出測試
1 1 true 0 10 10 9 8 7 6 5 4 3 2 1 size = 0