首先定义 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