Non generic Dequeue - Java Data Structure

Java examples for Data Structure:queue

Description

Non generic Dequeue

Demo Code

package com.company.stucts.queue;

import java.util.Arrays;

/**//from ww  w .java 2  s .  com
 * Double ended queue
 */
@SuppressWarnings({ "Duplicates", "WeakerAccess" })
public class Dequeue {
    private final Object[] data;
    private int head, tail, size;

    public Dequeue(int size) {
        data = new Object[size + 1];
        head = tail = 0;
        this.size = size;
    }

    public void pushFirst(Object o) {
        if (size() == size) {
            throw new IllegalStateException("Queue is full");
        }

        head = (--head + data.length) % data.length;
        data[head] = o;
    }

    public Object popFirst() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }

        Object o = data[head];
        data[head] = null;
        head = ++head % data.length;
        return o;
    }

    public void pushLast(Object o) {
        if (size() == size) {
            throw new IllegalStateException("Queue is full");
        }

        data[tail] = o;
        tail = ++tail % data.length;
    }

    public Object popLast() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        Object o = data[tail];
        data[tail] = null;
        tail = (--tail + data.length) % data.length;
        return o;
    }

    public boolean isEmpty() {
        return head == tail;
    }

    public int size() {
        if (head > tail) {
            return data.length - head + tail;
        } else {
            return tail - head;
        }
    }

    @Override
    public String toString() {
        return "Queue: " + "\n" + "data[]: " + Arrays.toString(data) + "\n"
                + "data[] length: " + data.length + "\n" + "size: "
                + size() + "\n" + "head: " + head + "\n" + "tail: " + tail;
    }

    public static void main(String[] args) {
        Dequeue dequeue = new Dequeue(4);
        dequeue.pushLast(1);
        dequeue.pushLast(2);
        dequeue.pushLast(3);
        dequeue.pushLast(4);
        dequeue.popLast();
        dequeue.pushFirst(5);
        System.out.println(dequeue);
    }
}

Related Tutorials