Jump to content

Circular buffer / queue visualization


Botre

Recommended Posts

Cookie pls doge.png

 

168ab2ab8a9b66755aa657a154a9ba8f.gif

package org.bjornkrols.botre.datastructures.queue;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by Bjorn on 25/05/2015.
 * Last edit: 25/05/2015.
 */
public class CircularArrayQueue<T> implements Queue<T>, Iterable<T> {

    private T[] queue;

    private int front, insert, size;

    public CircularArrayQueue(int capacity){
        queue = (T[]) new Object[capacity];
    }

    /**
     * Inserts the element at the rear of the queue.
     * If the queue is full, the oldest value will be removed and the the second oldest element will become the front element.
     */
    @Override
    public void enqueue(T element) {
        queue[insert] = element;
        insert = (insert + 1) % queue.length;
        if (isFull()) {
            front = (front + 1) % queue.length;
        } else {
            size++;
        }
    }

    @Override
    public T dequeue() {
        if (size == 0) {
            throw new NoSuchElementException("Queue is empty.");
        }
        T element = queue[front];
        queue[front] = null;
        front = (front + 1) % queue.length;
        size--;
        return element;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == queue.length;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<T> iterator() {
        return new QueueIterator();
    }

    public class QueueIterator implements Iterator<T> {

        private int current = front;
        private int i;

        @Override
        public boolean hasNext() {
            return i < queue.length;
        }

        @Override
        public T next() {
            T value = queue[current];
            current = (current + 1) % queue.length;
            i++;
            return value;
        }

    }

}
Edited by Botre
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...