Last active
October 1, 2025 13:26
-
-
Save pastuhov/d8f12c88a53f8267298b5a292a0d2af5 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 queue | |
| // Queue is a FIFO collection. | |
| // | |
| // Concurrency: not safe for concurrent use. | |
| type Queue[T any] struct { | |
| elements []T | |
| head int | |
| } | |
| func (q *Queue[T]) Push(element T) { | |
| q.elements = append(q.elements, element) | |
| } | |
| func (q *Queue[T]) Pop() (T, bool) { | |
| if q.head >= len(q.elements) { | |
| var zero T | |
| return zero, false | |
| } | |
| v := q.elements[q.head] | |
| q.head++ | |
| if q.head > 1024 && q.head*2 >= len(q.elements) { | |
| q.elements = append([]T(nil), q.elements[q.head:]...) | |
| q.head = 0 | |
| } | |
| return v, true | |
| } | |
| func (q *Queue[T]) Len() int { | |
| return len(q.elements) - q.head | |
| } |
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 queue_test | |
| import ( | |
| "queue" | |
| "testing" | |
| ) | |
| func TestQueue(t *testing.T) { | |
| queue := &queue.Queue[int]{} | |
| queue.Push(1) | |
| queue.Push(2) | |
| queue.Push(3) | |
| if l := queue.Len(); l != 3 { | |
| t.Errorf("Expected 3, got: %v", l) | |
| } | |
| if num, _ := queue.Pop(); num != 1 { | |
| t.Errorf("Expected 1, got: %v", num) | |
| } | |
| if num, _ := queue.Pop(); num != 2 { | |
| t.Errorf("Expected 2, got: %v", num) | |
| } | |
| if num, _ := queue.Pop(); num != 3 { | |
| t.Errorf("Expected 3, got: %v", num) | |
| } | |
| if _, ok := queue.Pop(); ok == true { | |
| t.Errorf("Expected false, got: %v", ok) | |
| } | |
| if l := queue.Len(); l != 0 { | |
| t.Errorf("Expected 0, got: %v", l) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment