From d9251b87592f94719710d66d17c768aaa164aec3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Tue, 16 Oct 2018 23:12:25 +0800 Subject: [PATCH] Create 232. Implement Queue using Stacks.md --- 232. Implement Queue using Stacks.md | 62 ++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 232. Implement Queue using Stacks.md diff --git a/232. Implement Queue using Stacks.md b/232. Implement Queue using Stacks.md new file mode 100644 index 0000000..5d63dc6 --- /dev/null +++ b/232. Implement Queue using Stacks.md @@ -0,0 +1,62 @@ +# [232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/) +# 思路 +用栈实现队列。 +设置两个栈stk1和stk2,stk1中的元素是按照正常入栈顺序排的,stk2则是逆序,且同一时刻stk1和stk2至少一个为空。 +若stk1不空,对队列入队的话直接对stk1入栈即可,否则要将stk2中所有元素pop到stk1中后再对stk1入栈。 +若stk2不空,对队列出队的话直接对stk2出栈即可,否则要将stk1中所有元素pop到stk2中后再对stk2出栈。 +# C++ +``` +class MyQueue { +private: + stackstk1; + stackstk2; +public: + /** Initialize your data structure here. */ + MyQueue() { + + } + /** Push element x to the back of queue. */ + void push(int x) { + if(stk1.empty()){ + int tmp; + while(!stk2.empty()){ + tmp = stk2.top(); + stk2.pop(); + stk1.push(tmp); + } + } + stk1.push(x); + } + /** Removes the element from in front of queue and returns that element. */ + int pop() { + int tmp; + if(stk2.empty()){ + while(!stk1.empty()){ + tmp = stk1.top(); + stk1.pop(); + stk2.push(tmp); + } + } + tmp = stk2.top(); + stk2.pop(); + return tmp; + } + + /** Get the front element. */ + int peek() { + if(stk2.empty()){ + int tmp; + while(!stk1.empty()){ + tmp = stk1.top(); + stk1.pop(); + stk2.push(tmp); + } + } + return stk2.top(); + } + /** Returns whether the queue is empty. */ + bool empty() { + return stk1.empty() && stk2.empty(); + } +}; +```