队列OJ题(二)

简介: ✅每日一练:232. 用栈实现队列 - 力扣(LeetCode)

思想: 这里需要2个栈来实现,把元素全部放到第一个栈中,再将第一个栈的元素放到第二个栈中,此时栈顶的元素就是我们要出队列的元素,依次下去可以完成操作;

e234d89b3dc341c2874a5ea4547c3854 (1).png

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 fals
importjava.util.Stack;
/*** Created with IntelliJ IDEA.* Description:* User: Snk* Date: 2023-02-07* Time: 12:50*/classMyQueue {
privateStack<Integer>stack1;
privateStack<Integer>stack2;
publicMyQueue() {
this.stack1=newStack<>();
this.stack2=newStack<>();
    }
publicvoidpush(intx) {
stack1.push(x);
    }
publicintpop() {
if(empty()){
return-1;
        }
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
            }
        }
returnstack2.pop();
    }
publicintpeek() {
if(empty()){
return-1;
        }
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
            }
        }
returnstack2.peek();
    }
publicbooleanempty() {
returnstack1.isEmpty() &&stack2.isEmpty();
    }
}
目录
相关文章
|
4月前
|
存储
leetcode:232. 用栈实现队列
leetcode:232. 用栈实现队列
19 0
|
6月前
Leetcode232.用栈实现队列
Leetcode232.用栈实现队列
25 0
LeetCode | 232. 用栈实现队列
LeetCode | 232. 用栈实现队列
|
18天前
|
C语言
Leetcode每日一题——“用栈实现队列”
Leetcode每日一题——“用栈实现队列”
|
4月前
|
Java C++ Python
leetcode-232:用栈实现队列
leetcode-232:用栈实现队列
21 0
|
5月前
|
Java C++
【剑指offer】-两个栈来实现一个队列-05/67
【剑指offer】-两个栈来实现一个队列-05/67
|
6月前
|
C语言
232.用栈实现队列(LeetCode)
232.用栈实现队列(LeetCode)
|
11月前
栈和队列OJ题:LeetCode--232.用栈实现队列
LeetCode--232.用栈实现队列:详细题解以及图解和完整代码。
47 0
|
11月前
栈和队列OJ题:LeetCode--225.用队列实现栈
LeetCode--225.用队列实现栈:详细题解以及图解和完整代码。
65 0
|
12月前
|
C语言
leetcode232. 用栈实现队列
leetcode232. 用栈实现队列
72 0