Skip to content

Instantly share code, notes, and snippets.

@benstone1
Created February 20, 2018 16:47
Show Gist options
  • Save benstone1/dd9889a38dd170db487d44a35678f15b to your computer and use it in GitHub Desktop.
Save benstone1/dd9889a38dd170db487d44a35678f15b to your computer and use it in GitHub Desktop.
Queue
class LLNode<Key> {
let val: Key
var next: LLNode?
init(val: Key) {
self.val = val
}
}
struct Queue<T> {
private var head: LLNode<T>?
private var tail: LLNode<T>?
var isEmpty: Bool {
return head == nil
}
mutating func enQueue(_ newElement: T) {
let newNode = LLNode(val: newElement)
guard let tail = tail else {
self.head = newNode
self.tail = newNode
return
}
tail.next = newNode
self.tail = newNode
}
mutating func deQueue() -> T? {
guard let oldHead = head else {
return nil
}
self.head = oldHead.next
if oldHead.next == nil {
self.tail = nil
}
return oldHead.val
}
func peek() -> T? {
return self.head?.val
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment