Skip to content

Instantly share code, notes, and snippets.

@jyaunches
Created September 28, 2017 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyaunches/c8633c7805a886c1beb40dca1fc5192d to your computer and use it in GitHub Desktop.
Save jyaunches/c8633c7805a886c1beb40dca1fc5192d to your computer and use it in GitHub Desktop.
Linked list implementation in Swift using Sequence protocol
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