第五章 栈与队列part01
今日任务:
● 理论基础
● 232.用栈实现队列
● 225. 用队列实现栈
理论基础
栈:先进后出。
如图所示:
一种通俗易懂的方式就是,栈就是只有一个口,先进去的是落在最底下,所以是最后才能出来。就如同吃东西一样,吃完后如果你消化不好,吐出来就是一种先进后出。
队列:先进先出
如图所示:
一种通俗易懂的方式就是,队列,就是一种排队的方式,先到的先进行手续,如银行排队等等,队列有两个口,如果比喻吃东西的话就是吃进去拉出来就是一种先进先出。
232.用栈实现队列
力扣链接:232. 用栈实现队列 - 力扣(LeetCode)
解题思路: 此处使用的是两个栈来实现一个队列的方式,一个负责进入栈,一个负责出栈。 困难点:每次出队列时,先判断stackout是否为空,为空的话需要将stackIn的元素全部倒入stackOut中。
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<Integer>();
stackOut = new Stack<Integer>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpStackIn();
return stackOut.pop();
}
public int peek() {
dumpStackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void dumpStackIn(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225. 用队列实现栈
力扣链接:225. 用队列实现栈 - 力扣(LeetCode)
解题思路:使用一个队列来模拟栈,每次poll时,都要将队列除第一个外的所有元素重新加入队列中。 此处使用队列的实现类为 LinkedList<>();
队列自身的方法:
- add() 添加元素
- poll() 弹出最先进入的元素
- size() 获取队列的大小
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
}
public int pop() {
rePosition();
return queue.poll();
}
public int top() {
rePosition();
int result = queue.poll();
queue.add(result);
return result;
}
public boolean empty() {
return queue.isEmpty();
}
public void rePosition(){
int size = queue.size();
size--;
while(size-->0)
queue.add(queue.poll());
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/