Last active
May 8, 2017 19:33
-
-
Save stephen-francis/4a902b7c7d6bfa4a93d7bab21546622a to your computer and use it in GitHub Desktop.
Simple linked list in Swift
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
| 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