需求
实现一个栈(Stack)和队列(Queue).
栈:后进先出
队列:先进先出
图示
栈
队列
代码
栈 (数组实现)
import java.util.Arrays;
import java.util.NoSuchElementException;
public class Stack<T> {
private static final int DEFAULT_CAPACITY = 10;
private Object[] elementData;
private int top;
public Stack() {
initStack();
}
public int size() {
return top + 1;
}
private void initStack() {
top = -1;
ensureCapacity(DEFAULT_CAPACITY);
}
public void push(T t) {
if (top + 1 == elementData.length)
ensureCapacity((elementData.length << 1) + 1);
elementData[++top] = t;
}
public T pop() {
if (empty())
throw new NoSuchElementException();
return (T) elementData(top--);
}
public boolean empty() {
return top == -1;
}
private void ensureCapacity(int newCapacity) {
if (top + 1 >= newCapacity)
return;
Object[] old = elementData;
elementData = new Object[newCapacity];
for (int i = 0; i <= top; i++) {
elementData[i] = old[i];
}
}
@SuppressWarnings("unchecked")
private T elementData(int index) {
return (T) elementData[index];
}
@Override
public String toString() {
return Arrays.toString(elementData);
}
}
队列 (链表实现)
public class Queue<T> {
public Node<T> beginMarker;
public Node<T> endMarker;
public int size;
public Queue() {
initQueue();
}
private void initQueue() {
beginMarker = new Node<T>(null, null, null);
endMarker = new Node<T>(null, beginMarker, null);
beginMarker.next = endMarker;
size = 0;
}
public int size() {
return size;
}
public boolean empty() {
return size == 0;
}
public void enqueue(T t) {
beginMarker.next = beginMarker.next.prev = new Node<T>(t, beginMarker,
beginMarker.next);
size++;
}
public T dequeue() {
if (size == 0)
return null;
Node<T> p = endMarker.prev;
p.prev.next = endMarker;
endMarker.prev = p.prev;
size--;
return p.data;
}
private static class Node<T> {
public T data;
public Node<T> prev;
public Node<T> next;
public Node(T data, Node<T> prev, Node<T> next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
}