Skip to content

Instantly share code, notes, and snippets.

@cgoldsby
Last active March 18, 2017 13:56
Show Gist options
  • Save cgoldsby/5c54bfff3a374e2f9cce8b44bdcf868f to your computer and use it in GitHub Desktop.
Save cgoldsby/5c54bfff3a374e2f9cce8b44bdcf868f to your computer and use it in GitHub Desktop.
MiSwift Challenge #2 - Linked List
//: Playground - noun: a place where people can play
import Foundation
class Node<T> {
let value: T
var next: Node<T>?
init(value: T) {
self.value = value
}
}
class LinkedList<T>: Sequence, CustomStringConvertible, ExpressibleByArrayLiteral {
private (set) var head: Node<T>?
private (set) var tail: Node<T>?
func append(_ value: T) {
let node = Node(value: value)
if let head = head {
head.next = node
}
else {
head = node
}
tail = node
}
// MARK: - ExpressibleByArrayLiteral
required init(arrayLiteral elements: T...) {
for element in elements {
append(element)
}
}
// MARK: - Sequence
func makeIterator() -> AnyIterator<T> {
var node = head
return AnyIterator {
defer { node = node?.next }
return node?.value
}
}
// MARK: CustomStringConvertible
var description: String {
return map { $0 }.description
}
}
let linkedList = LinkedList<Int>() // []
linkedList.append(1) // [1]
linkedList.append(2) // [1, 2]
let emojis: LinkedList = ["🌊", "🚘"]
emojis.head?.value // "🌊"
emojis.tail?.value // "🚘"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment