前言
本文主要介绍循环队列的设计,以及栈和队列的相互实现。
一、循环队列
力扣链接:link
1.1实现思路
我这里是用数组,且以牺牲空间的方法实现的,及在创建时多加一个空间
1.定义两个变量front——指向对头,rear——指向队尾
2.入队时,用rear=(rear+1)%elem.length;来更新rear的位置。
3.出队时,用 front=(front+1)%elem.length;来更新front的位置。
4. 判断队列是否满时,用rear+1)%elem.length==front;判断队列是否满了,即rear与front再次相遇。
5.获取队尾元素,对0位置单独判断,其他位置rear-1即为所在下标。
1.2具体实现
class MyCircularQueue {
public int[] elem;
public int rear;
public int front;
public MyCircularQueue(int k) {
elem=new int[k+1];
}
public boolean enQueue(int value) {
if(isFull()){
return false;
}
elem[rear]=value;
rear=(rear+1)%elem.length;
return true;
}
public boolean deQueue() {
if(isEmpty()){
return false;
}
front=(front+1)%elem.length;
return true;
}
public int Front() {
if(isEmpty()){
return -1;
}
return elem[front];
}
public int Rear() {
if(isEmpty()){
return -1;
}
if(rear==0){
return elem[elem.length-1];
}
return elem[rear-1];
}
public boolean isEmpty() {
return rear==front;
}
public boolean isFull() {
return (rear+1)%elem.length==front;
}
}
二、用栈实现队列
力扣链接:link
2.1实现思路
利用两个栈模拟实现队列
入队列:stack1模拟入队列,所有入队列的元素都放入到stack1中
出队列:stack2模拟出队列,当stack2为空时,将stack1中所有元素导入到stack2中
stack2中pop一个元素
获取队头元素:如果stack2是空,将stack1中所有元素导入stack2中,然后peek()一个元素
2.2具体实现
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (empty()) {
return -1;
}
while (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int peek() {
if (empty()) {
return -1;
}
int tmp = -1;
while (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
tmp = stack2.pop();
stack2.push(tmp);
return tmp;
}
public boolean empty() {
return stack1.empty() && stack2.empty();
}
}
三、用队列实现栈
力扣链接: link
3.1实现思路
1.入栈时,如果栈是空的,直接入第一个队列,如果栈不为空,哪个队列为空,入哪个队列
2.出栈时,出不为空的队列,出size-1个入到另一个为空的队列中,最后再出一个,即为要获取的元素
3.获取栈顶元素不删除,即在出队列时,全出且全入,并记录最后一个出栈的值,返回所记录的值
3.2具体实现
class MyStack {
Queue<Integer> que1;
Queue<Integer> que2;
public MyStack2() {
que1 = new LinkedList<>();
que2 = new LinkedList<>();
}
public void push(int x) {
if (empty()) {
que1.offer(x);
return;
}
if (!que1.isEmpty()) {
que1.offer(x);
} else {
que2.offer(x);
}
}
public int pop() {
if (empty()) {
return -1;
}
if (!que1.isEmpty()) {
int size = que1.size();
for (int i = 0; i < size - 1; i++) {
que2.offer(que1.poll());
}
return que1.poll();
} else {
int size = que2.size();
for (int i = 0; i < size - 1; i++) {
que1.offer(que2.poll());
}
return que2.poll();
}
}
public int top() {
if (empty()) {
return -1;
}
if (!que1.isEmpty()) {
int size = que1.size();
int tmp = -1;
for (int i = 0; i < size; i++) {
tmp = que1.poll();
que2.offer(tmp);
}
return tmp;
} else {
int size = que2.size();
int tmp = -1;
for (int i = 0; i < size ; i++) {
tmp = que2.poll();
que1.offer(tmp);
}
return tmp;
}
}
public boolean empty() {
return que1.isEmpty() && que2.isEmpty();
}
}