From beebebcebb5de92dfdb724046c8561bdc6cbf7dc 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 22:17:21 +0800 Subject: [PATCH] Create 225. Implement Stack using Queues.md --- 225. Implement Stack using Queues.md | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 225. Implement Stack using Queues.md diff --git a/225. Implement Stack using Queues.md b/225. Implement Stack using Queues.md new file mode 100644 index 0000000..00f83cf --- /dev/null +++ b/225. Implement Stack using Queues.md @@ -0,0 +1,45 @@ +# [225. Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/) +# 思路 +用队列实现栈。 +栈是先进后出,队列是后进先出,所以要想用队列实现栈时为了返回栈顶元素就得完整pop一遍队列里的元素,或者在进队的时候就将栈顶元素移到队头,下面的代码采用后者思路。 +因为pop和top都要求找到栈顶元素,采用前者思路的话会产生混乱。 +注意学习stl中queue的一些操作:push、pop、front +# C++ +``` +class MyStack { +private: + queueq; +public: + /** Initialize your data structure here. */ + MyStack() { + } + + /** Push element x onto stack. */ + void push(int x) { // 先将x进队,然后再将x前面的元素依次pop出来并入队尾,这样x就位于队头了。 + q.push(x); + int tmp; + for(int i = 0; i < q.size() - 1; i++){ + tmp = q.front(); + q.pop(); + q.push(tmp); + } + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + int res = q.front(); + q.pop(); + return res; + } + + /** Get the top element. */ + int top() { + return q.front(); + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q.empty(); + } +}; +```