algo/swift/08_stack/StackBasedOnLinkedList.swift
2018-10-13 15:37:24 +08:00

38 lines
824 B
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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
while head.next != nil {
count += 1
}
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
}
}