Created
June 6, 2023 13:30
-
-
Save cod3smith/473f76428260b0ba836dbba3e0d0eda3 to your computer and use it in GitHub Desktop.
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
package main | |
type CircularQueue struct { | |
items []interface{} | |
head int | |
tail int | |
size int | |
} | |
func NewCircularQueue(k int) *CircularQueue { | |
return &CircularQueue{ | |
items: make([]interface{}, k), | |
head: -1, | |
tail: -1, | |
size: 0, | |
} | |
} | |
func (cq *CircularQueue) Enqueue(item interface{}) bool { | |
if cq.IsFull() { | |
return false | |
} | |
if cq.IsEmpty() { | |
cq.head = 0 | |
} | |
cq.tail = (cq.tail + 1) % len(cq.items) | |
cq.items[cq.tail] = item | |
cq.size++ | |
return true | |
} | |
func (cq *CircularQueue) Dequeue() interface{} { | |
if cq.IsEmpty() { | |
return nil | |
} | |
item := cq.items[cq.head] | |
if cq.head == cq.tail { | |
cq.head = -1 | |
cq.tail = -1 | |
} else { | |
cq.head = (cq.head + 1) % len(cq.items) | |
} | |
cq.size-- | |
return item | |
} | |
func (cq *CircularQueue) IsEmpty() bool { | |
return cq.size == 0 | |
} | |
func (cq *CircularQueue) IsFull() bool { | |
return cq.size == len(cq.items) | |
} | |
func (cq *CircularQueue) GetSize() int { | |
return cq.size | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment