javacodex.com
Java Examples
Java Examples
memu home questions

Double Ended Queue

A double-ended queue (dequeue, often abbreviated to deque, pronounced deck) is an abstract data type that generalizes a queue, for which elements can be added to or removed from either the front (head) or back (tail).

Source: (DoubleEndedQueue.java)

import java.util.ArrayList;
import java.util.List;
 
public class DoubleEndedQueue {
 
    private List<Integer> deque = new ArrayList<Integer>();
 
    //add element at the beginning of the queue
    public void insertFront(int item) {
        System.out.println("adding at front: " + item);
        deque.add(0, item);
        System.out.println(deque);
    }
 
    //add element at the end of the queue
    public void insertRear(int item) {
        System.out.println("adding at rear: " + item);
        deque.add(item);
        System.out.println(deque);
    }
 
    //remove an item from the beginning of the queue
    public void removeFront() {
        if (deque.isEmpty()) {
            System.out.println("Deque is empty.");
            return;
        }
        int rem = deque.remove(0);
        System.out.println("removed from front: " + rem);
        System.out.println(deque);
    }
 
    //remove an item from the beginning of the queue
    public void removeRear() {
        if (deque.isEmpty()) {
            System.out.println("Deque is empty.");
            return;
        }
        int rem = deque.remove(deque.size() - 1);
        System.out.println("removed from front: " + rem);
        System.out.println(deque);
    }
 
    //gets the element from the front without removing it
    public int peakFront() {
        int item = deque.get(0);
        System.out.println("Element at first: " + item);
        return item;
    }
 
    //get the element from the rear without removing it
    public int peakRear() {
        int item = deque.get(deque.size() - 1);
        System.out.println("Element at rear: " + item);
        return item;
    }
 
    public static void main(String a[]) {
        DoubleEndedQueue deq = new DoubleEndedQueue();
        deq.insertFront(100);
        deq.insertRear(55);
        deq.removeFront();
        deq.insertFront(21);
        deq.removeRear();
        deq.insertFront(98);
        deq.insertRear(5);
        deq.insertFront(43);
        deq.removeRear();
        deq.removeRear();
        deq.peakRear();
        deq.peakFront();
    }
}

Output:

$ java DoubleEndedQueue
adding at front: 100
[100]
adding at rear: 55
[100, 55]
removed from front: 100
[55]
adding at front: 21
[21, 55]
removed from front: 55
[21]
adding at front: 98
[98, 21]
adding at rear: 5
[98, 21, 5]
adding at front: 43
[43, 98, 21, 5]
removed from front: 5
[43, 98, 21]
removed from front: 21
[43, 98]
Element at rear: 98
Element at first: 43

Contact: javacodex@yahoo.com