Can anyone suggest Go container for simple and fast FIF/queue, Go has 3 different containers: heap
, list
and vector
. Which one is more suitable to implement a queue?
To implement a queue using array, create an array arr of size n and take two variables front and rear both of which will be initialized to 0 which means the queue is currently empty. Element rear is the index upto which the elements are stored in the array and front is the index of the first element of the array.
It's better to use ArrayDeque instead of LinkedList when implementing Stack and Queue in Java. ArrayDeque is likely to be faster than Stack interface (while Stack is thread-safe) when used as a stack, and faster than LinkedList when used as a queue.
Queue follows the FIFO (First In, First Out) order. This means that the element is inserted in the queue at the end and removed from the queue at the beginning. The Java queue interface provides all the methods of Collection interface like insertion, deletion, etc.
Data Structures queue Stack One end is always used to insert data (enqueue) and the other is used to remove data (dequeue).
In fact, if what you want is a basic and easy to use fifo queue, slice provides all you need.
queue := make([]int, 0) // Push to the queue queue = append(queue, 1) // Top (just get next element, don't remove it) x = queue[0] // Discard top element queue = queue[1:] // Is empty ? if len(queue) == 0 { fmt.Println("Queue is empty !") }
Of course, we suppose that we can trust the inner implementation of append and slicing so that it avoid useless resize and reallocation. For basic usage, this is perfectly sufficient.
Surprised to see no one has suggested buffered channels yet, for size bound FIFO Queue anyways.
//Or however many you might need + buffer. c := make(chan int, 300) //Push c <- value //Pop x <- c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With