Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
queue
communitycreator

How to remove the first element from a DoubleLinkedQueue in Dart

Surabhi Sharma

The dart:collection library provides the advance collection support for the Dart language apart from the basic collections already provided by the dart:core library.

It contains the DoubleLinkedQueue<E> class which implements the abstract Queue<E> class, using a doubly-linked list.

The removeFirst() method

The DoubleLinkedQueue<E> class contains the removeFirst() method, which removes and returns the first element of the queue.

A queue is a FIFOFirst In First Out data structure. In a queue, the element that is added first will be deleted first.

  • This method modifies the state of the queue.
  • This method throws an unhandled exception if it is called on an empty queue.

Syntax

E removeFirst()

Arguments

  • This method does not take any arguments.

Return values

  • This method removes and returns the first element of the queue.
  • This is a constant-time operation.
Removing the first element of the queue using the removeFirst() method

Code

First, we import the dart:collection library into our program.

import 'dart:collection'; 
void main() { 
   var animalQueue = DoubleLinkedQueue<String>();
   
   animalQueue.add("Monkey"); 
   animalQueue.add("Lion"); 
   animalQueue.add("Tiger");   
   
   print('Printing Queue Elements');
   print(animalQueue); 

   var elem1 = animalQueue.removeFirst();
   print('Removing ${elem1} from Queue using removeFirst()');

   print('Printing Queue Elements');
   print(animalQueue); 
}  

Explanation

  • We created an instance of a DoubleLinkedQueue class of type String.
  • Next, we added the strings "Monkey", "Lion", and "Tiger" to the queue using the add() method.
  • The queue elements are displayed as {Monkey, Lion, Tiger}, and all the elements are added to the end of the queue because the queue is a FIFO data structure.
  • Now, we remove call the removeFirst() method and store the return value in a variable.
  • Then we display the removed item and all the queue elements once more, and we see that "Monkey" is removed from the queue. The queue elements are displayed using the print() function of the core library.

RELATED TAGS

dart
queue
communitycreator
RELATED COURSES

View all Courses

Keep Exploring