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() {
pre();
return stackout.pop();
}
public int peek() {
pre();
return stackout.peek();
}
public boolean empty() {
return stackin.isEmpty()&&stackout.isEmpty();
}
public void pre(){
if(!stackout.isEmpty())
return;
else{
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();
*/
这道题目对于理解队列和栈都有很好的作用,适合我这种基础理解不到位的
class MyStack {
Queue<Integer> queue1 = new ArrayDeque<>();
Queue<Integer> queue2 = new ArrayDeque<>();
public MyStack() {
}
public void push(int x) {
while(queue1.size()>0)
{
queue2.add(queue1.poll());
}
queue1.add(x);
while(queue2.size()>0)
{
queue1.add(queue2.poll());
}
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
/**
* 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();
*/
这道题目看着和上一道很像,其实思路很不一样,掌握栈和队列的基本函数
以上两道题目都属于自己肯定做不出来系列