Last active
December 7, 2019 15:53
-
-
Save tesarwijaya/bb393d62c5bb2295153fd7866cfdf55d to your computer and use it in GitHub Desktop.
Queue
This file contains 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 | |
import "fmt" | |
// Queue ... | |
type Queue struct { | |
Head int | |
Tail int | |
Size int | |
Items []interface{} | |
} | |
// Enqueue Add element to end of queue | |
func (q *Queue) Enqueue(v interface{}) { | |
if q.IsEmpty() { | |
q.Head = q.Head + 1 | |
q.Tail = q.Tail + 1 | |
q.Items[q.Head] = v | |
} else { | |
q.Tail = q.Tail + 1 | |
q.Items[q.Tail] = v | |
} | |
} | |
// Dequeue Remove element from front of queue | |
func (q *Queue) Dequeue() interface{} { | |
v := q.Items[q.Head] | |
q.Items = q.Items[1:] | |
q.Tail = q.Tail - 1 | |
return v | |
} | |
// IsEmpty Check if queue is empty | |
func (q *Queue) IsEmpty() bool { | |
return q.Head == -1 && q.Tail == -1 | |
} | |
// IsFull Check if queue is full | |
func (q *Queue) IsFull() bool { | |
return q.Tail == q.Size-1 | |
} | |
// Peek Get the value of the front of queue without removing it | |
func (q *Queue) Peek() interface{} { | |
return q.Items[q.Tail] | |
} | |
func (q *Queue) PrintQueue() { | |
fmt.Println("Head: ", q.Head) | |
fmt.Println("Tail: ", q.Tail) | |
fmt.Println("Items: ", q.Items) | |
} | |
func InitQueue(max int) *Queue { | |
return &Queue{ | |
Head: -1, | |
Tail: -1, | |
Items: make([]interface{}, max), | |
Size: max, | |
} | |
} | |
func main() { | |
q := InitQueue(5) | |
q.Enqueue(5) | |
q.Enqueue(2) | |
q.Enqueue(3) | |
q.Enqueue(7) | |
q.Enqueue(6) | |
q.PrintQueue() | |
q.Dequeue() | |
q.PrintQueue() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment