1.双端队列类设计
public static class Node<T>{
public T value;
public Node<T> last;
public Node<T> next;
public Node(T data){
value = data;
}
}
//双向队列
public static class DoubleEndsQueue<T>{
public Node<T> head;
public Node<T> tail;
//1.从头部增加节点
public void addFromHead(T value){
Node<T> cur = new Node<>(value);
if(head == null){
head = cur;
tail = cur;
}else {
cur.next = head;
head.last = cur;
head = cur;
}
}
//2.从尾部增加节点
public void addFromTail(T value){
Node<T> cur = new Node<>(value);
if(head == null){
head = cur;
tail = cur;
}else {
tail.next = cur;
cur.last = tail;
tail = cur;
}
}
//3.从头部删除节点,并返回删除节点的值
public T deleteFromHead(){
//(1)判断是否为空
if(head == null)
return null;
Node<T> cur = head;
//(2)判断是否只有一个节点
if(head == tail){
head = null;
tail = null;
}else {
head = head.next;
cur.next = null;
head.last = null;
}
return cur.value;
}
//4.从尾部删除节点,并返回删除节点的值
public T deleteFromTail(){
//(1)判断是否为空
if(head == null)
return null;
Node<T> cur = head;
//(2)判断是否只有一个节点
if(head == tail){
head = null;
tail = null;
}else {
tail = tail.last;
cur.last = null;
tail.next = null;
}
return cur.value;
}
public boolean isEmpty(){
return head == null;
}
}
2.栈的实现
private static class DoubleQueueStack<T>{
private DoubleEndsQueue<T> queue;
public DoubleQueueStack() {
queue = new DoubleEndsQueue<T>();
}
public void push(T value){
queue.addFromHead(value);
}
public T pop(){
return queue.deleteFromHead();
}
public boolean isEmpty(){
return queue.isEmpty();
}
}
3.队列的实现
private static class DoubleQueue<T>{
private DoubleEndsQueue<T> queue;
public DoubleQueue(){
queue = new DoubleEndsQueue<T>();
}
public void push(T value){
queue.addFromHead(value);
}
public T pop(){
return queue.deleteFromTail();
}
public boolean isEmpty(){
return queue.isEmpty();
}
}