Created
September 28, 2017 16:30
-
-
Save jyaunches/c8633c7805a886c1beb40dca1fc5192d to your computer and use it in GitHub Desktop.
Linked list implementation in Swift using Sequence protocol
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
class Link<T> { | |
let value: T | |
let nextLink: Link<T>? | |
init(_ value: T, next: Link<T>?){ | |
self.value = value | |
self.nextLink = next | |
} | |
} | |
class LinkedLink<T> : Sequence, IteratorProtocol { | |
var currentNode : Link<T>? | |
init(head: Link<T>) { | |
currentNode = head | |
} | |
func next() -> T? { | |
if let next = currentNode?.nextLink { | |
currentNode = next return next.value | |
} | |
return nil | |
} | |
} | |
let elementFour = Link(4, next: nil) | |
let elementThree = Link(3, next: elementFour) | |
let elementTwo = Link(2, next: elementThree) | |
let elementOne = Link(1, next: elementTwo) | |
let linkedList = LinkedLink(head: elementOne) | |
for item in linkedList { | |
print(item) | |
} | |
// prints 2 | |
// prints 3 | |
// prints 4 | |
linkedList.contains(2) //true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment