文章目录
题目
leetcode641 设计循环双端队列
思路
代码
java
import java.util.Deque;
import java.util.LinkedList;
/**
* @Author: ggdpzhk
* @CreateTime: 2024-08-03
* 641 双端队列:利用双向链表和动态数组实现
*/
public class _016_DeQueue {
/*提交时改名为MyCircularDeque1
* 其实内部就是双向链表
* 常数操作慢,但是leetcode数据量太小了,看不出劣势
* */
class MyCircularDeque1 {
//LinkedList就是Java里面自带的双端队列
public Deque<Integer> deque = new LinkedList<Integer>();
public int size;//链表里面有几个数字
public int limit;//限制双端列表里同时不能超过 的数字
public MyCircularDeque1(int k) {
size = 0;
limit = k;
}
public boolean insertFront(int value) {
if(isFull()){
return false;
}else{
deque.offerFirst(value);
size++;
return true;
}
}
public boolean insertLast(int value) {
if (isFull()){
return false;
}else{
deque.offerLast(value);
size++;
return true;
}
}
public boolean deleteFront() {
if(isEmpty()){
return false;
}else{
deque.pollFirst();
size--;
return true;
}
}
public boolean deleteLast() {
if(isEmpty()){
return false;
}else{
deque.pollLast();
size--;
return true;
}
}
public int getFront() {
if(isEmpty()){
return -1;
}
return deque.peekFirst();
}
public int getRear() {
if(isEmpty()){
return -1;
}
return deque.peekLast();
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == limit;
}
}
//用固定数组实现双端队列
//主要就是处理边界问题
class MyCircularDeque2 {
public int[] deque;
public int l,r,size,limit;//l,r表左右两个边界 []
public MyCircularDeque2(int k) {
deque = new int[k];
size = 0;
limit = k;
}
public boolean insertFront(int value) {
if (isFull()){
return false;
}else{
if(isEmpty()){
l = r = 0;
deque[0] = value;
}else{
l = l == 0 ? (limit - 1) : (l - 1);
deque[l] = value;
}
size++;
return true;
}
}
public boolean insertLast(int value) {
if (isFull()){
return false;
}else{
if(isEmpty()){
l = r = 0;
deque[0] = value;
}else{
r = r == limit - 1 ? 0 : r + 1;
deque[r] = value;
}
size++;
return true;
}
}
public boolean deleteFront() {
if(isEmpty()){
return false;
}else{
l = l == (limit-1) ? 0 : l + 1;
}
size--;
return true;
}
public boolean deleteLast() {
if(isEmpty()){
return false;
}else{
r = r == 0 ? (limit - 1) : (r - 1);
}
size--;
return true;
}
public int getFront() {
if (isEmpty()){
return -1;
}
return deque[l];
}
public int getRear() {
if (isEmpty()){
return -1;
}
return deque[r];
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == limit;
}
}
}
运行结果
问题
为什么能直接调用方法名
同一个类中的方法名能互相调用
- 那改为if(deque.isFull())可以吗?
可以,但是不好