数组实现栈
public class StackByArray<T> {
private int top = 0;
private Object[] stack;
public StackByArray() {
stack = new Object[10];
}
public void push(T t) {
expandCapacity(stack.length + 1);
stack[top] = t;
top++;
}
public T pop() {
T t = peek();
if (top > 0) {
stack[top - 1] = null;
top--;
}
return t;
}
public T peek() {
T t = null;
if (top > 0) {
t = (T) stack[top - 1];
}
return t;
}
public boolean isEmpty() {
return top == 0;
}
public void expandCapacity(int size) {
int len = stack.length;
if (size > len) {
size = size * 3 / 2 + 1;
stack = Arrays.copyOf(stack, size);
}
}
}
链表实现栈
public class StackByList<T> {
class Node<T> {
private T t;
private Node<T> next;
}
public Node<T> head;
public StackByList() {
head = null;
}
public void push(T t) {
if (t == null) {
throw new NullPointerException();
}
if (head == null) {
head = new Node<>();
head.t = t;
head.next = null;
} else {
Node<T> temp = head;
head = new Node<>();
head.t = t;
head.next = temp;
}
}
}