java implementation of Deque

 Deque(double ended Queue) is a type of queue. The elements can be inserted and deleted in both the ends. Deque is implemented in java by the concept of ‘ArrayDeque’.

What is ArrayDeque?

              It is a class available in java. ArrayDeque -Array Double Ended Queue which implement deque in java. It creates a resizable array for storing the queue elements.

Features of ArrayDeque:

  • ·       It holds light weight memory.
  • ·       Fast access to elements.
  • ·       Time performance is constant.
  • ·       Resizable.

Implementation of deque in java:

It uses built in packages java.util.ArrayDeque, java.util.deque.

Steps to follow:

  • Creation: An object is created for ‘ArrayDeque’.
  • Insertion: To insert the data, ‘addFirst’,’addLast’,’offerFirst’ ,’offerLast’ functions are used.
  • Removal: To delete the element, it uses ‘removeFirst’ and ‘removeLast’.
  • Peek: It extracts the elements from the queue. ‘peekFirst’ and ‘peekLast’ are used.

Program:

import java.util.ArrayDeque;

import java.util.Deque;

public class ArrayDequeSample {

    public static void main(String[] args) {

        // Create an object for deque using ArrayDeque

        Deque<Integer> deque1 = new ArrayDeque<>();

        // insert the elements to the deque

        deque1.addFirst(21);   // insert element to the front end

        deque1.addLast(34);    // insert element to the rear end

        deque1.offerFirst(10); // insert element to the front

        deque1.offerLast(9);  // insert element to the rear

        deque1.offerFirst(57);// insert element to the front

        deque1.offerLast(80);// insert element to the rear

        // Printing the elements in the deque

        System.out.println("The elements of the Deque: " + deque1);

        // extract and delete the elements from the deque

        System.out.println("First element is deleted: " + deque1.removeFirst());

        System.out.println("Last element is deleted: " + deque1.removeLast());

        // The elements in the deque after removals

        System.out.println("The elements of Deque after removals: " + deque1);

        // Extract the elements without deleting them

        System.out.println("The first element is: " + deque1.peekFirst());

        System.out.println("The last element is: " + deque1.peekLast());

    }

}

Output:

C:\raji\blog>javac ArrayDequeSample.java

C:\raji\blog>java ArrayDequeSample

The elements of the Deque: [57, 10, 21, 34, 9, 80]

First element is deleted: 57

Last element is deleted: 80

The elements of Deque after removals: [10, 21, 34, 9]

The first element is: 10

The last element is: 9

This is the way of implementing the deque using ArrayDeque. This is one of the easiest method. Happy coding!!!

No comments:

Post a Comment