---------------🎈🎈题目链接 用队列实现栈🎈🎈-------------------
---------------🎈🎈题目链接 用栈实现队列🎈🎈-------------------文章来源:https://www.toymoban.com/news/detail-807762.html
文章来源地址https://www.toymoban.com/news/detail-807762.html
队列的相关操作
创建队列
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();
*/
到了这里,关于【用队列实现栈】【用栈实现队列】Leetcode 232 225的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!