Swift Algorithm 一 Stack

使用Swift实现数据结构——栈,同时,实现栈的操作:push、pop和peek。

栈的基本操作

栈结构类似于数组,只不过其操作受限。对栈的操作有三种:

  1. 向栈顶部添加元素,称为 push 操作;
  2. 将栈顶元素移除,称为 pop 操作;
  3. 获取栈顶元素,称为 peek 操作

为什么会有这样的操作呢?因为在许多算法中,我们需要向一个临时列表中添加一个元素,在后续的操作中又要将这个元素移除掉,比如 iOS app 中的导航栏的 push 和 pop 操作就是这样子的。

Stack 的操作顺序是后进先出,即最后一个入栈的元素第一个被移除。

Swift 实现栈

STACK

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
```
### PUSH

### POP

### PEEK



## 测试

## 拓展
```Swift
public struct Stack<T: Comparable> {
fileprivate var array = [T]()

public var isEmpty: Bool {
return array.isEmpty
}

public var count: Int {
return array.count
}

public mutating func push(_ element: T) {
array.append(element)
}

public mutating func pop() -> T? {
return array.popLast()
}

public var peek: T? {
return array.last
}
}
-------------本文结束谢谢欣赏-------------
Alice wechat