Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
class MyQueue { Stack<Integer> end = new Stack<>(); Stack<Integer> front = new Stack<>(); // Push element x to the back of queue. public void push(int x) { end.push(x); } // Removes the element from in front of queue. public void pop() { if(front.isEmpty()) { while(!end.isEmpty()) { front.push(end.pop()); } } if(!front.isEmpty()) front.pop(); } // Get the front element. public int peek() { if(front.isEmpty()) { while(!end.isEmpty()) { front.push(end.pop()); } } return front.peek(); } // Return whether the queue is empty. public boolean empty() { return front.isEmpty() && end.isEmpty(); } }
相关推荐
232.Implement_Queue_using_Stacks用栈实现队列【LeetCode单题讲解系列】
推前LeetCode_232--Implement-Queue-using-Stacks 使用堆栈实现队列的以下操作。 push(x) -- 将元素 x 推到队列的后面。 pop()——从队列前面移除元素。 peek() -- 获取最前面的元素。 empty() -- 返回队列是否为空...
leetcode卡LeetCode-Queue-Stack-Card LeetCode“队列与堆栈”卡片问题的章节明智解决方案
力扣C++刷题指南教程,总结归纳得很不错
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
看leetcode吃力资料结构与演算法学习笔记 Week1 中秋节放假 Week2 说明上课方式与计分规则 Week3 完成LeetCode 707. Design Linked List Week4 完成LeetCode 155. Min Stack 完成LeetCode 232. Implement Queue ...
leetcode 答案Leetcode---数据库 我对 Leetcode 数据库问题的回答
LeetCode题解 - Java语言实现-181页.pdf
彩色版本 正版 pdf 精讲数据结构 + 算法 链表 树 图表 贪心算法 指针 动态规划 查找算法
leetcode1-300.docx
leetcode 答案leetcode--python Leetcode 的答案
500195422331430LeetCode题解 - Java语言实现.zip
leetcode 答案LeetCode--哈希表 以上是我对“哈希表”问题的回答,都被leetcode的判断所接受。
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Using Python3 题目源自 。使用 Python3 实现。 目录 两数之和: 两数相加: 无重复字符的最长子串: Z字形变换: 宝石与石头: 寻找两个有序数组的中位数: 最长回文子串: 删除链表倒数第N个节点: 合并K个排序链表: 跳跃...
leetcode 1 -200题所有源码 有问题私聊我
leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...