Queues in JavaScript (Data Structures)
Short and Precise Js code to create a queue.
A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
Implementing queue using arrays:
- Using the push and shift methods:
2. Using the unshift and pop methods:
Creating a queue using a linked list:
Todos:
- Enqueue
- Dequeue
Creating a node: It contains a value and a pointer.
Queue class: It contains the first value, last value, and length.
Enqueue: adding to the end of the queue
- This function accepts some value.
- Create a new node using that value passed in the function.
- If there are no nodes in the queue, set this node to be the first and last property of the queue.
- Otherwise, set the next property on the current last to be that node, then set the last property of the queue to be that node.
- Increment the length of the queue by one.
Dequeue: removing the node from the beginning of the queue.
- If there is no first property then return null.
- Store the first property in a variable.
- See if the first is the same as the last (checking if there’s only one node in the queue), and set the first and last to be null.
- If there is more than one node, set the first property to be the next property of the first.
- Decrement the size by one.
- Return the value of the node dequeued.
Time Complexity of a Queue:
- Access: O(n)
- Search: O(n)
- Insertion: O(1)
- Removal: O(1)