Skip to content

Instantly share code, notes, and snippets.

@acrookston
Last active February 2, 2017 21:51
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 acrookston/e3269e3ffc5f68ab48a8a3e856007d17 to your computer and use it in GitHub Desktop.
Save acrookston/e3269e3ffc5f68ab48a8a3e856007d17 to your computer and use it in GitHub Desktop.
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