题干:https://leetcode.com/problems/design-circular-queue/
这题感觉蛮简单的,可能因为条件给得比较充分,约束多,变数小吧。
思路就是建立一个整型数组,构造函数按照尺寸初始化之,然后保存两个下标指示变量,分别用于指示下一个将要插入的位置和当前队头index,每次deque或者enque都要更新这两个指示量中的一个。注意所谓circle用循环index操作就好。没什么花头,一次过:
package com.example.demo.leetcode; import java.util.Arrays; public class MyCircularQueue { int[] content; int nextTail = 0; int currentHead = 0; /** Initialize your data structure here. Set the size of the queue to be k. */ public MyCircularQueue(int k) { content = new int[k]; Arrays.fill(content, -1); } /** Insert an element into the circular queue. Return true if the operation is successful. */ public boolean enQueue(int value) { if(isFull()){ return false; } content[nextTail] = value; nextTail = nextPointer(nextTail); return true; } private int nextPointer(int currentPointer){ int p = currentPointer+1; if(p>content.length-1){ p=p%content.length; } return p; } /** Delete an element from the circular queue. Return true if the operation is successful. */ public boolean deQueue() { if(isEmpty()){ return false; } content[currentHead]=-1; currentHead=nextPointer(currentHead); return true; } /** Get the front item from the queue. */ public int Front() { if(isEmpty()){ return -1; }else{ return content[currentHead]; } } /** Get the last item from the queue. */ public int Rear() { if(isEmpty()){ return -1; } return content[previousPointer(nextTail)]; } private int previousPointer(int index){ int p = index-1; if(p<0){ p = p+content.length; } return p; } /** Checks whether the circular queue is empty or not. */ public boolean isEmpty() { for(int i=0;i<content.length;i++){ if(content[i]!=-1){ return false; } } return true; } /** Checks whether the circular queue is full or not. */ public boolean isFull() { for(int i=0;i<content.length;i++){ if(content[i]==-1){ return false; } } return true; } public static void main(String[] args) { MyCircularQueue obj = new MyCircularQueue(10); System.out.println("init queue of size:10"); boolean param_1 = obj.enQueue(3); System.out.println(" enque 3: "+ param_1); boolean param_2 = obj.deQueue(); System.out.println("after dequeue"); int param_3 = obj.Front(); System.out.println("this is front after dequeue:"+param_3); int param_4 = obj.Rear(); System.out.println("this is rear after dequeue: "+ param_4); boolean param_5 = obj.isEmpty(); System.out.println("is empty?(yes) : "+ param_5); boolean param_6 = obj.isFull(); System.out.println("is full?(no): "+ param_6); } }