队列queue
底层通过无头双向链表实现,下面让我们实现一下queue常用的操作方法
class ListNode{
ListNode next; //指针后继域
ListNode prev; //指针前驱域
int val; //指针数值域
public ListNode(int val) {
this.val = val;
}
}
public class MyQueue {
private ListNode first; //指向队列头
private ListNode last; //指向队列尾
//实现队列的方法
public boolean offer(int val){
//new要插入的结点
ListNode node = new ListNode(val);
//第一次插入结点
if(this.first == null){
this.first = this.last = node;
}
//第二次插入
this.last.next = node;
node.prev = last; //新结点prev指向last
this.last = node;
return true;
}
//得到队头元素并删除
public int poll(){
//如果队列为空,不能弹出元素
if(isEmpty()){
throw new RuntimeException("队列为空");
}
int value = this.first.val; //保存队列头元素
this.first = this.first.next;
this.first.prev = null; //删除头结点后,下一个结点的prev指向null
return value;
}
//得到队头元素不删除
public int peek(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
int value = this.first.val; //保存队列头元素
return value;
}
public boolean isEmpty(){
if(this.first == null && this.last == null){
return true;
}
return false;
}
@Override
public String toString() {
return "MyQueue{" +
"first=" + first +
", last=" + last +
'}';
}
}
调试用例:
在poll语句处打了断点,通过调试,我们可以发现链表具体情况