Debian Codegraph @

queues/linkedlistqueue/linkedlistqueue.go

raw symbols SCIP
1 // Copyright (c) 2021, Aryan Ahadinia. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package linkedlistqueue implements a queue backed by a singly-linked list.
6 //
7 // Structure is not thread safe.
8 //
9 // Reference: https://en.wikipedia.org/wiki/Queue_(abstract_data_type)
10 package linkedlistqueue
11
12 import (
13 "fmt"
14 "strings"
15
16 "github.com/emirpasic/gods/v2/lists/singlylinkedlist"
17 "github.com/emirpasic/gods/v2/queues"
18 )
19
20 // Assert Queue implementation
21 var _ queues.Queue[int] = (*Queue[int])(nil)
22
23 // Queue holds elements in a singly-linked-list
24 type Queue[T comparable] struct {
25 list *singlylinkedlist.List[T]
26 }
27
28 // New instantiates a new empty queue
29 func New[T comparable]() *Queue[T] {
30 return &Queue[T]{list: singlylinkedlist.New[T]()}
31 }
32
33 // Enqueue adds a value to the end of the queue
34 func (queue *Queue[T]) Enqueue(value T) {
35 queue.list.Add(value)
36 }
37
38 // Dequeue removes first element of the queue and returns it, or nil if queue is empty.
39 // Second return parameter is true, unless the queue was empty and there was nothing to dequeue.
40 func (queue *Queue[T]) Dequeue() (value T, ok bool) {
41 value, ok = queue.list.Get(0)
42 if ok {
43 queue.list.Remove(0)
44 }
45 return
46 }
47
48 // Peek returns first element of the queue without removing it, or nil if queue is empty.
49 // Second return parameter is true, unless the queue was empty and there was nothing to peek.
50 func (queue *Queue[T]) Peek() (value T, ok bool) {
51 return queue.list.Get(0)
52 }
53
54 // Empty returns true if queue does not contain any elements.
55 func (queue *Queue[T]) Empty() bool {
56 return queue.list.Empty()
57 }
58
59 // Size returns number of elements within the queue.
60 func (queue *Queue[T]) Size() int {
61 return queue.list.Size()
62 }
63
64 // Clear removes all elements from the queue.
65 func (queue *Queue[T]) Clear() {
66 queue.list.Clear()
67 }
68
69 // Values returns all elements in the queue (FIFO order).
70 func (queue *Queue[T]) Values() []T {
71 return queue.list.Values()
72 }
73
74 // String returns a string representation of container
75 func (queue *Queue[T]) String() string {
76 str := "LinkedListQueue\n"
77 values := []string{}
78 for _, value := range queue.list.Values() {
79 values = append(values, fmt.Sprintf("%v", value))
80 }
81 str += strings.Join(values, ", ")
82 return str
83 }
84
85 // Check that the index is within bounds of the list
86 func (queue *Queue[T]) withinRange(index int) bool {
87 return index >= 0 && index < queue.list.Size()
88 }