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.
class MyQueue { public Stack<Integer> stackPush; public Stack<Integer> stackPop; public MyQueue() { stackPush = new Stack<Integer>(); stackPop = new Stack<Integer>(); } // Push element x to the back of queue. public void push(int x) { stackPush.push(x); } // Removes the element from in front of queue. public void pop() { if (stackPop.isEmpty() && stackPush.isEmpty()) { ; } else if (stackPop.isEmpty()) { while (!stackPush.isEmpty()) { stackPop.push(stackPush.pop()); } } stackPop.pop(); } // Get the front element. public int peek() { if (stackPop.isEmpty() && stackPush.isEmpty()) { return 0; } else if (stackPop.isEmpty()) { while (!stackPush.isEmpty()) { stackPop.push(stackPush.pop()); } } return stackPop.peek(); } // Return whether the queue is empty. public boolean empty() { return stackPop.isEmpty() && stackPush.isEmpty(); } }
相关推荐
232.Implement_Queue_using_Stacks用栈实现队列【LeetCode单题讲解系列】
Implement Queue using Stacks Week5 完成LeetCode 147. Insertion Sort List 完成作业Quick sort Week6 10/11 国庆弹性放假 Week7 完成作业Heap sort Week8 完成作业Merge sort Week9 Week10 完成作业Binary Search...
Implement Queue using Stacks 旋转数组的最小数字 153. Find Minimum in Rotated Sorted Array 斐波那契数列 509. Fibonacci Number 跳台阶 70. Climbing Stairs 变态跳台阶 矩形覆盖 二进制中1的个数 191. Number ...
Implement Queue using Stacks 二叉树 二叉树的遍历 Binary Tree Preorder Traversal Binary Tree Inorder Traversal Binary Tree Postorder Traversal Binary Tree Level Order Traversal Binary Tree Level Order ...
推前LeetCode_232--Implement-Queue-using-Stacks 使用堆栈实现队列的以下操作。 push(x) -- 将元素 x 推到队列的后面。 pop()——从队列前面移除元素。 peek() -- 获取最前面的元素。 empty() -- 返回队列是否为空...
* [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap](https://github.com/kamyu104/LeetCode#heap) * [Tree](https://github.com/kamyu104/LeetCode#tree) * [Hash Table]...
queue.push(1); queue.push(2); queue.peek(); // returns 1 queue.pop(); // returns 1 queue.empty(); // returns false 笔记: 您必须仅使用堆栈的标准操作——这意味着只有推到顶部、从顶部查看/弹出、大小和为...
Table of ContentsBuilding Stacks for Application State ManagementCreating Queues for In-Order ExecutionsUsing Sets and Maps for Faster ApplicationsUsing Trees for Faster Lookup and ...
To be able to implement the ADTs stack, queue, and deque using Python lists. To understand the performance of the implementations of basic linear data structures. To understand prefix, infix, and ...
Understand and implement classic data structures and algorithms using JavaScript About This Book Learn how to use the most used data structures such as array, stack, list, tree, and graphs with real-...
The C++ Standard Library A Tutorial and Reference (2nd Edition)+cppstdlib-code.zip C++标准库(第二版)英文版.pdf 非扫描版+源代码 Prefaceto the SecondEdition xxiii Acknowledgments for the Second...