本文主要是介绍[LeetCode]232.Implement Queue using Stacks,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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, and is 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).
思路
两个栈模拟队列
代码
/*---------------------------------------
* 日期:2015-08-01
* 作者:SJF0115
* 题目: 232.Implement Queue using Stacks
* 网址:https://leetcode.com/problems/implement-queue-using-stacks/
* 结果:AC
* 来源:LeetCode
* 博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;class Queue {
public:// Push element x to the back of queue.void push(int x) {firStack.push(x);}// Removes the element from in front of queue.void pop(void) {if(!secStack.empty()){secStack.pop();return;}//ifif(firStack.empty()){return;}//ifwhile(!firStack.empty()){secStack.push(firStack.top());firStack.pop();}//whilesecStack.pop();}// Get the front element.int peek(void) {if(!secStack.empty()){return secStack.top();}//if//no pop or peek operations will be called on an empty queueif(firStack.empty()){return -1;}//ifwhile(!firStack.empty()){secStack.push(firStack.top());firStack.pop();}//whilereturn secStack.top();}// Return whether the queue is empty.bool empty(void) {return firStack.empty() && secStack.empty();}
private:stack<int> firStack;stack<int> secStack;
};int main(){Queue q;for(int i = 0;i < 5;++i){q.push(i);}//forwhile(!q.empty()){cout<<q.peek()<<" ";q.pop();}//whileq.push(8);cout<<q.peek()<<endl;q.pop();cout<<q.peek()<<endl;return 0;
}
这篇关于[LeetCode]232.Implement Queue using Stacks的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!