理论基础
了解一下 栈与队列的内部实现机智,文中是以C++为例讲解的。
文章讲解:
Leetcode 232.用栈实现队列
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html
重点: 主要是熟练使用java关于栈和队列操作的一些语法
思路图:
自己写的代码:
// push(x) -- 将一个元素放入队列的尾部。
// pop() -- 从队列首部移除元素。
// peek() -- 返回队列首部的元素。
// empty() -- 返回队列是否为空。
// pop和peek功能相似,可封装一个方法,让他们两一起调用
// empty要求进栈和出栈都不能为空
class MyQueue {
// 定义全局变量
Stack<Integer> stackIn;
Stack<Integer> stackOut;
/** 初始化数据结构. */
public MyQueue() {
stackIn = new Stack<>(); // 负责进栈
stackOut = new Stack<>(); // 负责出栈
}
/** 将一个元素放入队列的尾部. */
public void push(int x) {
stackIn.push(x);
}
/** 从队列的开头移除并返回元素. */
public int pop() {
dumpstackIn();
return stackOut.pop();
}
/** 返回队列开头的元素. */
public int peek() {
dumpstackIn();
return stackOut.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
private void dumpstackIn(){
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()){
// 将入栈队头的元素压入出栈队尾的位置
stackOut.push(stackIn.pop());
}
}
}
Leetcode 225. 用队列实现栈
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html 思路图:
自己写的代码:
class MyStack {
Queue<Integer> queue1; // 和栈中保持一样元素的队列
Queue<Integer> queue2; // 辅助队列
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue2.offer(x); // 先放在辅助队列中
while (!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer> queueTemp;
queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}