Last active
February 2, 2017 21:51
-
-
Save acrookston/e3269e3ffc5f68ab48a8a3e856007d17 to your computer and use it in GitHub Desktop.
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 LinkedListNode<T> { | |
var next : LinkedListNode<T>? | |
var value: T | |
var count : Int { | |
return next == nil ? 1 : next!.count + 1 | |
} | |
init(_ value: T, _ next: LinkedListNode<T>?=nil) { | |
self.value = value | |
self.next = next | |
} | |
func nodeAt(_ index: Int) -> LinkedListNode<T>? { | |
if index == 0 { | |
return self | |
} | |
if let node = next { | |
return node.nodeAt(index - 1) | |
} | |
return nil | |
} | |
} | |
class LinkedList<T> { | |
typealias Node = LinkedListNode<T> | |
var head : Node? | |
weak var tail : Node? | |
var count : Int { | |
return head == nil ? 0 : head!.count | |
} | |
subscript(index: Int) -> T? { | |
return nodeAt(index)?.value | |
} | |
init() {} | |
func nodeAt(_ index: Int) -> Node? { | |
if let node = head { | |
return node.nodeAt(index) | |
} | |
return nil | |
} | |
func push(_ value: T) { | |
let node = Node(value) | |
if head == nil { | |
head = node | |
tail = node | |
} else if let last = tail { | |
last.next = node | |
tail = node | |
} | |
} | |
func append(_ value: T) { | |
head = Node(value, head) | |
} | |
@discardableResult func pop() -> T? { | |
guard let node = head else { return nil } | |
if head === tail { | |
tail = nil | |
} | |
return node.value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment