//使用双向链表实现队列
public class Code01_DoubleLinkedListToQueue {
public static class Node<V>{
public V value;
public Node<V> next;
public Node<V> last;
public Node(V v){
value = v;
next = null;
last = null;
}
}
public static class MyQueue<V>{
private Node<V> head;
private Node<V> tail;
private int size;
public void pusHead(V value){
Node<V> cur = new Node<V>(value);
if(head == null){
head = cur;
tail = cur;
}else{
//新加的next节点指向当前的头部
cur.next = head;
//当前头部的last节点指向新加的节点
head.last = cur;
//让头部变成新加节点
head = cur;
}
size++;
}
public void pusTail(V value){
Node<V> cur = new Node<V>(value);
if(tail == null){
head = cur;
tail = cur;
}else{
//新加的节点last指针指向当前的尾部
cur.last = tail ;
//当前尾部的next节点指向新增的节点
tail.next = cur;
//让尾部变成新增节点
tail = cur;
}
size++;
}
public V pollHead(){
V ans = null;
if(head == null){
return ans;
}
size -- ;
ans = head.value;
if(head == tail ){
head = null;
tail = null;
}else{
head = head.next;
head.last = null;
}
return ans;
}
public V pollTail(){
V ans = null;
if(tail == null){
return ans;
}
size -- ;
ans = tail.value;
if(head == tail ){
head = null;
tail = null;
}else{
tail = tail.last;
tail.next = null;
}
return ans;
}
public V peekHead(){
V ans = null;
if(head != null){
ans = head.value;
}
return ans;
}
public V peekTail(){
V ans = null;
if(tail != null){
ans = tail.value;
}
return ans;
}
public boolean isEmpty(){
return size == 0 ? true:false;
}
public int size(){
return size;
}
public MyQueue(){
size = 0;
head = null;
tail = null;
}
}
}
code04-双向链表实现队列
最新推荐文章于 2024-07-24 15:22:10 发布