2018-10-13 15:37:24 +08:00
|
|
|
|
//
|
|
|
|
|
// Created by Jiandan on 2018/10/12.
|
|
|
|
|
// Copyright (c) 2018 Jiandan. All rights reserved.
|
|
|
|
|
//
|
|
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
|
|
struct StackBasedOnLinkedList<Element>: Stack {
|
|
|
|
|
private var head = Node<Element>() // 哨兵结点,不存储内容
|
|
|
|
|
|
|
|
|
|
// MARK: Protocol: Stack
|
|
|
|
|
|
|
|
|
|
var isEmpty: Bool { return head.next == nil }
|
|
|
|
|
|
|
|
|
|
var size: Int {
|
|
|
|
|
var count = 0
|
2019-03-11 23:12:30 +08:00
|
|
|
|
var cur = head.next
|
|
|
|
|
while cur != nil {
|
2018-10-13 15:37:24 +08:00
|
|
|
|
count += 1
|
2019-03-11 23:12:30 +08:00
|
|
|
|
cur = cur?.next
|
2018-10-13 15:37:24 +08:00
|
|
|
|
}
|
|
|
|
|
return count
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var peek: Element? { return head.next?.value }
|
|
|
|
|
|
|
|
|
|
func push(newElement: Element) -> Bool {
|
|
|
|
|
let node = Node(value: newElement)
|
|
|
|
|
node.next = head.next
|
|
|
|
|
head.next = node
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func pop() -> Element? {
|
|
|
|
|
let node = head.next
|
|
|
|
|
head.next = node?.next
|
|
|
|
|
return node?.value
|
|
|
|
|
}
|
|
|
|
|
}
|