swift实现栈和队列

在swift中并没有内设的栈和队列,接下来我们通过数组来实现栈和队列

栈的实现代码如下:

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
protocol Stack {
associatedtype Element
//是否为空
var isEmpty: Bool{ get }
//栈的大小
var Size: Int{ get }
//栈顶元素
var peek: Element? { get }
//入栈
mutating func push(_ newElement:Element)
//出栈
mutating func pop()->Element?
}

struct IntegerStack:Stack {
typealias Element = Int
private var stack = [Element]()
var isEmpty: Bool {return stack.isEmpty}
var Size: Int {return stack.count}
var peek: Int? {return stack.last}
mutating func push(_ newElement: Int) {
self.stack.append(newElement)
}
func pop() -> Int? {
return stack.last
}
}

队列的实现代码如下:

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
protocol Queue {
associatedtype Element
var isEmpty: Bool {get}
var Size: Int {get}
var Peek:Element? {get}
mutating func enQueue(_ newElement:Element)
mutating func deQueue()->Element?
}

struct IntergerQueue:Queue {
typealias Element = Int
private var left = [Element]()
private var right = [Element]()
var isEmpty: Bool {return left.isEmpty && right.isEmpty}
var Size: Int {return left.count + right.count}
var Peek: Element? {return left.isEmpty ? right.first : left.last}
mutating func enQueue(_ newElement: Int) {
right.append(newElement)
}
mutating func deQueue() -> Element? {
if left.isEmpty {
left = right.reversed()
right.removeAll()
}
return left.popLast()
}
}
-------评论系统采用disqus,如果看不到需要翻墙-------------