实现栈的基本方法
push(T t)元素入栈
T pop() 元素出栈
Tpeek() 查看栈顶元素
boolean isEmpty() 栈是否为空
基于数组实现栈
import java.util.Arrays;public class ArrayStack<T> {private Object[] stack;private int top;public ArrayStack() {this.stack = new Object[10];this.top = 0;}public boolean isEmpty() {return top == 0;}public void expand(int size) {int len = stack.length;if (size > len) {size = size * 3 / 2 + 1;stack = Arrays.copyOf(stack, size);}}public T pop() {T t = null;if (top > 0) {t = (T) stack[top--];}return t;}public void push(T t) {expand(top + 1);stack[top++] = t;}public T peek(){T t = null;if(top >0){t = (T) stack[top-1];}return t;}
}
基于链表实现栈
public class ListStack<T>{class Node<T> {public T t;public Node next;}private Node<T> head;public ListStack() {}public boolean isEmpty() {if(head == null){return true;}return false;}public void push(T t){if(head == null){head = new Node<T>();head.t = t;head.next = null;}Node<T> temp = new Node<T>();temp.t = t;temp.next = head;head = temp;}public T pop() {if(isEmpty()){return null;}T t = head.t;head = head.next;return t;}public T peek(){if(isEmpty()){return null;}T t = head.t;return t;}
}