algo/swift/08_stack/StackBasedOnLinkedList.swift

40 lines
874 B
Swift
Raw Normal View History

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
var cur = head.next
while cur != nil {
2018-10-13 15:37:24 +08:00
count += 1
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
}
}