Queue Basics
excerpt: This covers the implementation of enqueue and dequeue operations of a linked list based stack. tags: linked-list-traversal sentinel
A queue is a data structure where items are added and removed in first-in-first-out order. They are sometimes called FIFO lists or FIFOs. A queue is similar to grocery checkout line. People join the end of the line and wait their turn. When they get to the front of the line, the cashier checks out your items and give you a receipt.
The method that adds an item to a queue is called Enqueue and the item that removes an item from a queue is called Dequeue.
Linked-List Queues
Linked list can be used to implement a queue. Doubly linked list makes removing the last item from the queue easy. The enqueue method add a new node to the head of the list and the dequeue method removes the last node from the list. The following code shows the enqueue method to add an item in a linked-list stack.
|
|
This will add the node with value three to the beginning of the linked list.
The node class has getters and setters for getting and setting the values for the value, next and previous pointers.
|
|
The implementation of doubly linked list with the code for testing:
|
|
The dequeue method removes the item in the end of the doubly linked list. There must be an item in the queue to remove it. Otherwise, an exception will be thrown. The dequeue method will return the value of the node that was removed from the list.
|
|
The enqueue and dequeue operations implemented using doubly linked list have O(1) run times. The don’t need any extra space, so the space complexity is O(1).