public class MyQueue {
static class ListNode{
public int val;
public ListNode prev;
public ListNode next;
public ListNode(int val){
this.val=val;
}
}
public ListNode head;
public ListNode last;
public void offer(int val){
ListNode node=new ListNode(val);
if(head==null){
head=last=node;
}else{
//尾插法
last.next=node;
node.prev=last;
last=last.next;
}
}
public int poll(){
if(head==null){
return -1;
}
int ret=head.val;
if(head.next==null){//只有一个节点
head=last=null;
}else{
//头删
head=head.next;
head.prev=null;
}
return ret;
}
public int peek(){
if(head==null){
return -1;
}
return head.val;
}
public boolean isEmpty(){
return head==null;
}
}
class MyCircularQueue {
public int[] elem;
public int first;//first和last默认是0位置,不用初始化
public int last;
public MyCircularQueue(int k) {
elem=new int[k+1];
}
//入队列
public boolean enQueue(int value) {
if (isFull()){
return false;
}
elem[last]=value;
last=(last+1)%elem.length;
return true;
}
//出队列
public boolean deQueue() {
if (isEmpty()){
return false;
}
first=(first+1)% elem.length;
return true;
}
//得到对头元素,但不删除
public int Front() {
if (isEmpty()){
return -1;
}
return elem[first];
}
//得到队尾元素,但不删除
public int Rear() {
if (isEmpty()){
return -1;
}
int index=(last==0)?
elem.length-1 :last-1;
return elem[index];//这里不能直接用last-1,可能会越界
}
public boolean isEmpty() {
return first==last;
}
public boolean isFull() {
return (last+1)% elem.length==first;
}
}