Skip to content

Instantly share code, notes, and snippets.

@alanzeino
Created October 7, 2016 18:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanzeino/25fff2ec3c4cc00fb2ee9eb9eb1add2d to your computer and use it in GitHub Desktop.
Save alanzeino/25fff2ec3c4cc00fb2ee9eb9eb1add2d to your computer and use it in GitHub Desktop.
A simple LinkedList in Swift 3 using Sequence and IteratorProtocol
//: Playground - noun: a place where people can play
import Foundation
class Node {
let value: Any
var next: Node?
init(value: Any, next: Node?) {
self.value = value
self.next = next
}
}
class LinkedList: Sequence {
var head: Node?
// MARK: <Sequence>
func makeIterator() -> LinkedListIterator {
return LinkedListIterator(self)
}
}
struct LinkedListIterator: IteratorProtocol {
let linkedList: LinkedList
var current: Node?
init(_ linkedList: LinkedList) {
self.linkedList = linkedList
self.current = linkedList.head
}
mutating func next() -> Node? {
guard let thisCurrent = current else { return nil }
current = thisCurrent.next
return thisCurrent
}
}
let node3 = Node(value: 3, next: nil)
let node2 = Node(value: 2, next: node3)
let node1 = Node(value: 1, next: node2)
let linkedList = LinkedList()
linkedList.head = node1
for node in linkedList {
if let nodeInt = node.value as? Int {
print("\(nodeInt)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment