Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created May 12, 2022 16:44
Show Gist options
  • Save derekli66/e7f0fa5e7ef4b0d3c3cb7c86072ac014 to your computer and use it in GitHub Desktop.
Save derekli66/e7f0fa5e7ef4b0d3c3cb7c86072ac014 to your computer and use it in GitHub Desktop.
Queue Implementation
private class ListNode {
var next: ListNode?
var prev: ListNode?
var key: Int = 0
}
/*
push to back, peek/pop from front, size and is empty
*/
class Queue {
private var head: ListNode?
private var tail: ListNode?
private var count: Int = 0
func push(_ key: Int) {
let newNode = ListNode()
newNode.key = key
if head == nil {
head = newNode
tail = newNode
}
else {
tail?.next = newNode
tail = tail?.next
}
count += 1
}
func peak() -> Int {
return head?.key ?? 0
}
func popFront() -> Int {
let frontNode = head
head = head?.next
if head == nil {
tail = nil
}
count -= 1
return frontNode?.key ?? 0
}
func size() -> Int {
return count
}
func isEmpty() -> Bool {
return size() == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment