·
·
文章目录
  1. 题目介绍
  2. 复杂度
  3. 解题思路

Implement Queue using Stacks

题目介绍

LeetCode 232. Implement Queue using Stacks

复杂度

时间复杂度: O(n), 空间复杂度: O()

解题思路

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
55
56
class Queue {
private var array = [Int]()

func push(x: Int) {
array.append(x)
}

func pop() -> Int {
return array.removeFirst()
}

func empty() -> Bool {
return array.isEmpty
}

func peek() -> Int {
return array.first ?? -1
}
}

class MyStack {

var queue = Queue()
var temp = Queue()

/** Initialize your data structure here. */
init() {

}

/** Push element x onto stack. */
func push(_ x: Int) {
temp.push(x: x)
while !queue.empty() {
temp.push(x: queue.pop())
}
while !temp.empty() {
queue.push(x: temp.pop())
}
}

/** Removes the element on top of the stack and returns that element. */
func pop() -> Int {
return queue.pop()
}

/** Get the top element. */
func top() -> Int {
return queue.peek()
}

/** Returns whether the stack is empty. */
func empty() -> Bool {
return queue.empty()
}
}
**版权声明**

Ivan’s Blog by Ivan Ye is licensed under a Creative Commons BY-NC-ND 4.0 International License.
叶帆创作并维护的叶帆的博客博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于Ivan’s Blog | 叶帆的博客博客( http://yeziahehe.com ),版权所有,侵权必究。

本文链接:http://yeziahehe.com/2020/04/07/ImplementQueueUsingStacks/

支持一下
扫一扫,支持yeziahehe
  • 微信扫一扫
  • 支付宝扫一扫