Created
May 12, 2022 16:44
-
-
Save derekli66/e7f0fa5e7ef4b0d3c3cb7c86072ac014 to your computer and use it in GitHub Desktop.
Queue Implementation
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
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