Created
December 6, 2016 02:01
-
-
Save rchatham/d05570879d303ba2cfe1398cecb9c702 to your computer and use it in GitHub Desktop.
Queue using Node's in Swift
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
internal class Node<T> { | |
var data: T | |
var next: Node<T>? | |
init(data: T) { | |
self.data = data | |
} | |
} | |
internal struct Queue<T> { | |
var first, last: Node<T>? | |
mutating func dequeue() -> T? { | |
let pop = first?.data | |
first = first?.next | |
if first == nil { | |
last = nil | |
} | |
return pop | |
} | |
mutating func enqueue(data: T) { | |
if last == nil { | |
first = Node(data: data) | |
last = first | |
} else { | |
last?.next = Node(data: data) | |
last = last?.next | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment