Created
August 14, 2016 17:23
-
-
Save joanmolinas/ed7d6c37dc961248f308dbab776b1c36 to your computer and use it in GitHub Desktop.
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
import Foundation | |
class LinkedList<T : Equatable> { | |
private typealias Node = LinkedListNode<T> | |
private var _head : Node? | |
private var _tail : Node? | |
private var _size : UInt = 0 | |
//MARK : Public API | |
internal func front() -> T? { | |
return self._head?.value | |
} | |
internal func back() -> T? { | |
return self._tail?.value | |
} | |
internal func pushFront(node : T?) throws{ | |
guard let n = node else { | |
throw ManipulationErrors.InsertNilElement | |
} | |
if let h = self._head { | |
let newNode = Node() | |
newNode.value = n | |
newNode.next = h | |
self._head?.previous = newNode | |
self._head = newNode | |
} else { | |
self._head = Node() | |
self._head?.value = n | |
self._tail = self._head | |
} | |
self._size += 1 | |
} | |
internal func pushBack(node : T?) throws { | |
guard let n = node else { | |
throw ManipulationErrors.InsertNilElement | |
} | |
if let t = self._tail { | |
let newNode = Node() | |
newNode.value = n | |
newNode.previous = t | |
self._tail?.next = newNode | |
self._tail = newNode | |
} else { | |
try self.pushFront(n) | |
} | |
self._size += 1 | |
} | |
internal func popFront() throws { | |
guard !self.empty() else { | |
throw ManipulationErrors.PopEmpty | |
} | |
self._head = self._head?.next | |
if self._head == nil { | |
self._tail = self._head | |
} | |
self._size -= 1 | |
} | |
internal func popBack() throws { | |
guard !self.empty() else { | |
throw ManipulationErrors.PopEmpty | |
} | |
self._tail = self._tail?.previous | |
if self._tail == nil { | |
self._head = self._tail | |
} | |
self._size -= 1 | |
} | |
internal func size() -> UInt { | |
return self._size | |
} | |
internal func empty() -> Bool { | |
return self._head == nil | |
} | |
} | |
extension LinkedList : CustomStringConvertible { | |
var description: String { | |
var debug = "<\(LinkedList.self)> [" | |
while !self.empty() { | |
debug += "\(self.front()!)" | |
do { try self.popFront() } | |
catch {} | |
if !self.empty() { | |
debug += "," | |
} | |
} | |
debug += "]" | |
return debug | |
} | |
} | |
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
import Foundation | |
class LinkedListNode<T> { | |
var value : T! | |
var next : LinkedListNode<T>? | |
weak var previous : LinkedListNode<T>? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment