解题思路:采用两个栈,实现队列,一个用于进栈S1,一个用于出栈和取头元素S2。进栈时必须将S2中元素全部加入S1中,出栈时必须将S1中的元素加入S2中,才可以保证先进先出。判断为空时,S1,S2均为空。
Java代码实现:
class MyQueue {
private Stack stack1;
private Stack stack2;
MyQueue(){
stack1=new Stack();
stack2=new Stack();
}
// Push element x to the back of queue.
public void push(int x) {
if(stack2.isEmpty()) stack1.push(x);
else {
while(!stack2.isEmpty()){
stack1.push(stack2.peek());
stack2.pop();
}
stack1.push(x);
}
}
// Removes the element from in front of queue.
public void pop() {
if(stack1.isEmpty()) {
if(!stack2.isEmpty())
stack2.pop();
}
else {
while(!stack1.isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
stack2.pop();
}
}
// Get the front element.
public int peek() {
if(stack1.isEmpty()) {
if(!stack2.isEmpty())
return (int) stack2.peek();
return -1;
}
else {
while(!stack1.isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
return (int) stack2.peek();
}
}
// Return whether the queue is empty.
public boolean empty() {
if(stack1.isEmpty()&&stack2.isEmpty()) return true;
else return false;
}
}
原题地址:
https://leetcode.com/problems/implement-queue-using-stacks/
版权声明:本文为博主原创文章,未经博主允许不得转载。
分享到:
相关推荐
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...