Related Tags

julia
communitycreator

# How to create and use a Queue in Julia

Programming Bytes

## Overview

In Julia, the Queue data structure follows the FIFO (First In First Out) method, which means that the item first entered into the queue will be removed first.

### Example

Let’s look at a real-life example: a line of people waiting at a concert. A new person arriving would join the end of the line, while the person at the front of the line would leave the line and enter the venue.

Queue visualisation

### Operations

Queue mainly includes two operations:

• enqueue: It adds an element at the end of the Queue.
• dequeue: It removes the first element of the Queue.

### Code example

Below is a sample code for using a Queue in Julia:

using DataStructures

# create a new Queue
queue = Queue{Int}()

# enqueue an item to the top of the queue
enqueue!(queue, 1)
enqueue!(queue, 2)
enqueue!(queue, 3)

println("The queue is $(queue)") println("\nThe Length of queue is :", length(queue) ) println("\nThe First element of queue is :", first(queue) ) println("\nRemoving first element of queue is :", dequeue!(queue) ) println("\nThe queue is:$(queue)")

# emptying the queue
empty!(queue)

println("After Emptying queue is: \$(queue)")
Queue implementation

### Code explanation

• Line 4: We create a Queue object with the name queue.
• Lines 7 to 9: We use the enqueue!() method to insert three elements into the queue.
• Line 13: We use the length() method to get the number of elements of the queue.
• Line 14: We use the first() method to get the first element of the queue.
• Line 15: We use the dequeue!() method to remove the first element of the queue.
• Line 20: We use the empty() method to remove all elements of the queue.

RELATED TAGS

julia
communitycreator

CONTRIBUTOR

Programming Bytes
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time