Skip to content

Instantly share code, notes, and snippets.

@shanecowherd
Last active November 17, 2019 17:06
Show Gist options
  • Save shanecowherd/078ebac405be975ef33ad680c0e4abf3 to your computer and use it in GitHub Desktop.
Save shanecowherd/078ebac405be975ef33ad680c0e4abf3 to your computer and use it in GitHub Desktop.
LeetCode 622. Design Circular Queue
//https://leetcode.com/problems/design-circular-queue/
//Passed
//Runtime: 104 ms, faster than 78.33% of Swift online submissions for Design Circular Queue.
//Memory Usage: 21.7 MB, less than 100.00% of Swift online submissions for Design Circular Queue.
class Item {
let value: Int
var next: Item?
var prev: Item?
init(value: Int) {
self.value = value
}
}
class MyCircularQueue {
let max: Int
var count = 0
var startItem: Item?
var endItem: Item?
/** Initialize your data structure here. Set the size of the queue to be k. */
init(_ k: Int) {
self.max = k // Number of keys
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
func enQueue(_ value: Int) -> Bool {
//guard !isFull() else { return false }
let newItem = Item(value: value)
if startItem == nil && endItem == nil {
startItem = newItem
endItem = newItem
startItem?.next = endItem
startItem?.prev = endItem
endItem?.next = startItem
endItem?.prev = startItem
count = 1
return true
}
guard !isFull() else { return false }
endItem?.next = newItem
newItem.prev = endItem
endItem = newItem
if count < max {
count += 1
}
return true
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
func deQueue() -> Bool {
guard !isEmpty() else { return false }
endItem?.next = startItem?.next
endItem?.next?.prev = endItem
startItem = endItem?.next
count -= 1
if count == 0 {
endItem = nil
startItem = nil
}
return true
}
/** Get the front item from the queue. */
func Front() -> Int {
guard !isEmpty() else { return -1 }
return startItem?.value ?? -1
}
/** Get the last item from the queue. */
func Rear() -> Int {
guard !isEmpty() else { return -1 }
return endItem?.value ?? -1
}
/** Checks whether the circular queue is empty or not. */
func isEmpty() -> Bool {
return count == 0
}
/** Checks whether the circular queue is full or not. */
func isFull() -> Bool {
return count == max
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* let obj = MyCircularQueue(k)
* let ret_1: Bool = obj.enQueue(value)
* let ret_2: Bool = obj.deQueue()
* let ret_3: Int = obj.Front()
* let ret_4: Int = obj.Rear()
* let ret_5: Bool = obj.isEmpty()
* let ret_6: Bool = obj.isFull()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment