栈和队列的实际实现
双向链表实现
public class MyQueue<T> {
private Node<T> head;
private Node<T> tail;
public void push(T value) {
Node<T> node = new Node(value);
if (head == null) {
head = node;
tail = node;
} else {
node.next = head;
head.prev = node;
head = node;
}
}
public T pop() {
if (head == null)
return null;
Node node = tail;
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.prev;
node.prev = null;
tail.next = next;
}
return node.value;
}
public Boolean isEmpty() {
return head == null;
}
}
数组实现
public class MyQueue {
private int pushIndex = 0;
private int popIndex = 0;
private int size = 0;
private int limit = 0;
private final int[] arr;
public MyQueue(int limit) {
arr = new int[limit];
pushIndex = 0;
popIndex = 0;
size = 0;
this.limit = limit;
}
public void push(int value) {
if (size == limit) {
throw new RuntimeException("不能再添加了!");
}
size++;
arr[pushIndex] = value;
pushIndex = nextIndex(pushIndex);
}
public int pop() {
if (size == 0) {
throw new RuntimeException("不能再弹出了!");
}
size--;
int value = arr[popIndex];
popIndex = nextIndex(popIndex);
return value;
}
public Boolean isEmpty() {
return size == 0;
}
private int nextIndex(int index) {
return index == limit - 1 ? 0 : index + 1;
}
}