225.用队列实现栈[easy]

LeetCode 算法题停止更新,请移步至 GitHub

题目描述

使用队列实现栈的下列操作:

  • push(x) – 元素 x 入栈
  • pop() – 移除栈顶元素
  • top() – 获取栈顶元素
  • empty() – 返回栈是否为空

说明

你只能使用队列的基本操作– 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。

你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

解题方法

1.使用一个 queue

  1. push(x):a.push(x)

  2. pop():栈是先进后出,而队列是先进先出。用队列来实现栈的 pop() 方法,思路就是循环 size()-1 次,将队列前面的元素取出并重新 push 进队列的尾部。比如开始的队列是 1,2,3,4,5,当进行 pop() 的时候,队列会变成 2,3,4,5,1,然后再将 1 pop 出来。

  3. top():这里和上面的 pop() 思路是一样的,注意,这里是读取操作,不应该对队列原来的顺序进行改变。也就是说,读取到队列头部的元素后,应该再将头部的元素压入到尾部中,以恢复原来的顺序。

  4. empty():a.empty()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {

}

/** Push element x onto stack. */
void push(int x) {
a.push(x);
}

/** Removes the element on top of the stack and returns that element. */
int pop() {
int count = a.size();
while (count-- > 1) {
a.push(a.front());
a.pop();
}
int b = a.front();
a.pop();
return b;
}

/** Get the top element. */
int top() {
int count = a.size();
while (count-- > 1) {
a.push(a.front());
a.pop();
}
int b = a.front();
a.push(b);
a.pop();
return b;
}

/** Returns whether the stack is empty. */
bool empty() {
return a.empty();
}

private:
queue<int> a;
};

/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
状态 执行用时 内存消耗
通过 8 ms 8.9 MB

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2019 Acan's blog All Rights Reserved.

访客数 : | 访问量 :