How to use the pushfirst! method of CircularDeque in Julia

Overview

The pushfirst! method is used to add an element at the beginning of the CircularDeque object.

Note: CircularDeque is a double-ended queue implementation using a circular buffer of fixed capacity (while creating the deque, the capacity should be provided). It supports insertion and deletion on both ends.

Syntax

pushfirst!(deque_object, items...) -> collection

Parameter

This method takes an CircularDeque object and the values to be inserted as arguments.

Return value

This method returns the CircularDeque object, which is passed in the arguments.

Example

using DataStructures
#create a new CircularDeque object for 5 elements
deque = CircularDeque{Int}(5);
push!(deque,2);
push!(deque, 3);
push!(deque, 4);
println("\nDeque -> $(deque)")
# insert 0 and 1 at the beginning of the deque
pushfirst!(deque, 0, 1);
println("\nDeque -> $(deque)")

Explanation

  • Line 4: We create a CircularDeque object with the name deque. For this object, we set the capacity as 5, meaning it can hold 5 elements. Also, we set the elements of deque to be an integer datatype.
  • Lines 6–8: We add three integer elements, 2,3, and 4, to deque using the push! method.
  • Line 13: We use the pushfirst! method to add two elements, 0,1, at the beginning of the deque object. After calling this method, the elements of deque will be 0,1,2,3,4 .

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources