Created
October 7, 2016 18:42
-
-
Save alanzeino/25fff2ec3c4cc00fb2ee9eb9eb1add2d to your computer and use it in GitHub Desktop.
A simple LinkedList in Swift 3 using Sequence and IteratorProtocol
This file contains hidden or 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
//: 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