队头插入:队友front下标位置本身是有值的,所以要将front退后一位然后再赋值,不过要考虑是否为满或者数组越界情况 。
队尾删除:只需要rear位置减1,同时也要考虑是否为空和越界情况 。
具体实现代码:
public class MyCircularDeque {private int data[];// 数组容器private int front;// 头private int rear;// 尾private int maxsize;// 最大长度/*初始化 最大大小为k */public MyCircularDeque(int k) {data = https://www.isolves.com/it/cxkf/sf/2021-09-16/new int[k+1];front = 0;rear = 0;maxsize = k+1;}/** 头部插入 */public boolean insertFront(int value) {if(isFull())return false;else {front=(front+maxsize-1)%maxsize;data[front]=value;}returntrue;}/** 尾部插入 */public boolean insertLast(int value) {if(isFull())returnfalse;else{data[rear]=value;rear=(rear+1)%maxsize;}returntrue;}/** 正常头部删除 */public boolean deleteFront() {if (isEmpty())return false;else {front=(front+1)%maxsize;}returntrue;}/** 尾部删除 */public boolean deleteLast() {if(isEmpty())return false;else {rear=(rear+maxsize-1)%maxsize;}return true;}/** Get the front item*/public int getFront() {if(isEmpty())return -1;return data[front];}/** Get the last item from the deque. */public int getRear() {if(isEmpty())return -1;returndata[(rear-1+maxsize)%maxsize];}/** Checks whether the circular deque is empty or not. */public boolean isEmpty() {return front==rear;}/** Checks whether the circular deque is full or not. */public boolean isFull() {return (rear+1)%maxsize==front;}}总结对于队列来说数据结构相比栈复杂一些,但是也不是很难,搞懂先进先出然后用数组或者链表实现即可 。对于数组,队尾tail指向的位置是空的,而链表的front(head一样)为头指针为空的,所以在不同结构实现相同效果的方法需要注意一下 。
数组实现的循环队列能够很大程度利用数组空间,而双向队列则是既能当队列又能当栈的一种高效数据结构,掌握还是很有必要的 。
最后,笔者水平有限,如果有纰漏和不足之处还请指出 。另外,如果感觉不错可以点个三连!
关于作者:公众号:bigsai 头条号:程序员bigsai
推荐阅读
- 提高github访问速度,亲测可以
- 防晒|6个毁皮肤的坏习惯
- 女生可爱仙女味的qq昵称有哪些?
- 骨头汤的做法
- 红绿豆排骨汤的做法
- 氽猪肝汤
- 骨头汤
- 葱油鲈鱼的做法
- 炸五香的做法
- SATA、mSATA、M.2、PCIe!SSD接口那点事
