用队列实现栈和用栈实现队列

用两个栈来实现队列,思路和用数组实现队列一样

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
//用栈实现队列
struct QueueByStack{

var Peek: Int? {
mutating middleCaulate()
return rightStack?.peek
}

typealias Element = Int

private var leftStack:IntergerStack?
private var rightStack:IntergerStack?

init() {
leftStack = IntergerStack()
rightStack = IntergerStack()
}

var isEmpty: Bool {return leftStack!.isEmpty && rightStack!.isEmpty}
var Size: Int {return leftStack!.Size + rightStack!.Size}

mutating func middleCaulate(){
if leftStack!.isEmpty {
while !rightStack!.isEmpty{
leftStack!.push((rightStack?.pop())!)
}
}
}

mutating func enQueue(_ newElement: Int) {
rightStack?.push(newElement)
}

mutating func deQueue() -> Int? {
middleCaulate()
return leftStack?.peek
}


}

用两个队列来实现栈

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
struct StackByQueue {
private var queueA : IntergerQueue?
private var queueB : IntergerQueue?
init() {
queueA = IntergerQueue()
queueB = IntergerQueue()
}

var isEmpty: Bool{
get {
return queueA!.isEmpty && queueB!.isEmpty
}
}

var Size: Int {
get {
return queueA!.Size
}
}

var peek: Int?{
mutating get {
transfer()
let obj = queueB?.Peek
swap()
return obj
}
}

mutating func push(_ newElement:Int){
queueB?.enQueue(newElement)
}

mutating func pop()->Int?{
transfer()
let obj = queueB?.deQueue()
swap()
return obj
}

mutating func transfer() {
if queueB?.Size != 1{
queueA?.enQueue((queueB?.deQueue())!)
}
}
mutating func swap(){
(queueA,queueB) = (queueB,queueA)
}
}
-------评论系统采用disqus,如果看不到需要翻墙-------------