---------------题目链接 用队列实现栈-------------------
---------------题目链接 用栈实现队列-------------------
创建队列
Queue<Integer> myqueue = new LinkedList<>();
添加元素
myqueue.add();
队列最初的元素
myqueue.peek();
队列弹出元素:
myqueue.poll();
队列大小
myqueue.size();
队列是否为空
myqueue.isEmpty();
创建栈
Stack<Integer> mystack = new Stack<>();
添加元素
mystack.push();
栈顶元素
mystack.peek();
弹出栈顶元素:
mystack.pop();
栈大小
mystack.size();
栈是否为空
mystack.isEmpty();
class MyStack {
Queue<Integer> myqueue;
public MyStack() {
myqueue = new LinkedList<>();
}
public void push(int x) {
myqueue.add(x);
}
public int pop() {
for(int i = 0; i < myqueue.size()-1; i++){
myqueue.add(myqueue.poll());
}
return myqueue.poll();
}
public int top() {
int top;
for(int i = 0; i < myqueue.size()-1; i++){
myqueue.add(myqueue.poll());
}
top = myqueue.peek();
myqueue.add(myqueue.poll());
return top;
}
public boolean empty() {
if(myqueue.isEmpty()){
return true;
}
else return false;
}
}
/**
* 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();
*/
class MyQueue {
Stack<Integer> mystackin;
Stack<Integer> mystackout;
public MyQueue() {
mystackin = new Stack<>();
mystackout = new Stack<>();
}
public void push(int x) {
while(!mystackout.isEmpty()){
mystackin.push(mystackout.pop());
}
mystackin.push(x);
}
public int pop() {
while(!mystackin.isEmpty()){
mystackout.push(mystackin.pop());
}
return mystackout.pop();
}
public int peek() {
while(!mystackin.isEmpty()){
mystackout.push(mystackin.pop());
}
return mystackout.peek();
}
public boolean empty() {
if(mystackin.isEmpty() && mystackout.isEmpty()){
return true;
}
else return false;
}
}
/**
* 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();
*/