Created
October 31, 2018 06:37
-
-
Save teaualune/88c9d4800a381091f81b7e3fdf7d8e90 to your computer and use it in GitHub Desktop.
Basic one-way linked list implementation example in Swift 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* definition | |
*/ | |
indirect enum LinkedList<T> : Sequence { | |
case end | |
case node(value: T, next: LinkedList<T>) | |
init() { | |
self = .end | |
} | |
init(value: T) { | |
self = .node(value: value, next: .end) | |
} | |
mutating func push(_ item: T) { | |
self = .node(value: item, next: self) | |
} | |
mutating func pop() -> T? { | |
switch self { | |
case .end: | |
return nil | |
case .node(let value, let next): | |
self = next | |
return value | |
} | |
} | |
func makeIterator() -> LinkedList<T>.Iterator { | |
return Iterator(self) | |
} | |
struct Iterator : IteratorProtocol { | |
typealias Element = T | |
private var list: LinkedList<Element> | |
init(_ list: LinkedList<Element>) { | |
self.list = list | |
} | |
mutating func next() -> LinkedList<T>.Iterator.Element? { | |
switch self.list { | |
case .end: | |
return nil | |
case .node(let value, let nextList): | |
self.list = nextList | |
return value | |
} | |
} | |
} | |
} | |
/* | |
* usages | |
*/ | |
var linked = LinkedList<String>(value: "first") | |
linked.push("second") | |
print(linked) | |
for v in linked { | |
print(v) // second, first | |
} | |
if let value = linked.pop() { | |
print(value) // second | |
} | |
for v in linked { | |
print(v) // first | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment