KOKO-代码随想录算法训练营Day 10| 232|225
一、232 用栈实现队列
1.题目
https://leetcode.cn/problems/implement-queue-using-stacks/
2.代码
public class MyQueue232 {
int size;
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue232() {
size=0;
stack1=new Stack<>();
stack2=new Stack<>();
}
public void push(int x) {
size++;
if(stack1.isEmpty()){
stack1.push(x);
return;
}
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
stack1.push(x);
while (!stack2.isEmpty()){
stack1.push(stack2.pop());
}
}
public int pop() {
if(!stack1.isEmpty()){
size--;
return stack1.pop();
}
return -1;
}
public int peek() {
return stack1.peek();
}
public boolean empty() {
return size==0?true:false;
}
}
3.总结
用栈实现队列,我是定义了两个栈,在push的时候将栈1中元素弹出压到栈2中,将新加的元素压到栈底,在从栈顶元素拷贝进去。
卡哥是从弹出的时候对栈进行操作的,并且size可以不适用。
二、225. 用队列实现栈
1.题目
https://leetcode.cn/problems/implement-stack-using-queues/
2.代码
class MyStack {
Queue<Integer> que; //类似于栈
public MyStack() {
que=new ArrayDeque();
}
public void push(int x) {
que.add(x);
}
public int pop() {
changeState();
return que.poll();
}
private void changeState() {
int x=que.size();
x--;
while (x-->0){
que.add(que.poll());
}
}
public int top() {
int x=pop();
push(x);
return x;
}
public boolean empty() {
return que.isEmpty();
}
}
3.总结
使用队列,只需弹出的时候,将最后一个元素之前的所有元素重新插入队列就可以。
新插入的元素在队列尾部。
令:若用Deque,push,pop()就是对栈进行操作Deque可以当作栈使用。
此题用了Queue去实现。
PS:队列删除从对头删,队尾插入元素。