Skip to content

Instantly share code, notes, and snippets.

@stephen-francis
Last active May 8, 2017 19:33
Show Gist options
  • Select an option

  • Save stephen-francis/4a902b7c7d6bfa4a93d7bab21546622a to your computer and use it in GitHub Desktop.

Select an option

Save stephen-francis/4a902b7c7d6bfa4a93d7bab21546622a to your computer and use it in GitHub Desktop.
Simple linked list in Swift
class ListNode<T> {
var data: T
var next: ListNode?
init(_ data: T) {
self.data = data
}
// nodes are inserted at the end of the list
func insert(_ node: ListNode) {
if next == nil {
next = node
} else {
next?.insert(node)
}
}
}
class LinkedList<T> {
var head: ListNode<T>? // head is nil when list is empty
func insert(_ node: ListNode<T>) {
guard let head = head else {
self.head = node
return
}
var current = head
while let next = current.next {
current = next
}
current.next = node
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment