public class MyQueue {
private static class ListNode{
int value;
ListNode prev;
ListNode next;
public ListNode(int value){
this.value = value;
}
}
public ListNode head;
public ListNode tail;
public int size = 0;
public void offer(int e){
ListNode node = new ListNode(e);
if (head==null){
head=node;
}else {
tail.next = node;
node.prev = tail;
// tail = tail.next;
}
tail = node;
size++;
}
public int poll(){
// 先判断是否是空队列
if (isEmpty()){
throw new RuntimeException("队列为空");
}
// 此时队列不为空,记录出队节点的值
int headValue = head.value;
// 向后移动head
head = head.next;
if (head ==null){
tail = null;
}else{
// 处理前驱节点
head.prev.next = null;
// 处理当前head的prev
head.prev = null;
}
// 调整size的值
size--;
return headValue;
}
public int peek(){
// 先判断是否是空队列
if (isEmpty()){
throw new RuntimeException("队列为空");
}
int headValue = head.value;;
return headValue;
}
public int size() {
return size;
}
private boolean isEmpty() {
return size==0;
}
public void display() {
StringBuilder sb = new StringBuilder();
sb.append("[");
ListNode current = head;
while (current != null) {
sb.append(current.value);
if (current.next != null) {
sb.append(", ");
}
current = current.next;
}
sb.append("]");
System.out.println(sb);
}
}
[java数据结构]双向链表实现队列
最新推荐文章于 2022-11-28 09:52:31 发布