Skip to content

Instantly share code, notes, and snippets.

@Krasnyanskiy
Created January 3, 2017 00:21
Show Gist options
  • Save Krasnyanskiy/b8e192a593d4505686e4c5d4c4448f77 to your computer and use it in GitHub Desktop.
Save Krasnyanskiy/b8e192a593d4505686e4c5d4c4448f77 to your computer and use it in GitHub Desktop.
-java: queue
package com.hackerrank.challenges;
import java.util.Arrays;
/**
* @author Alexander Krasniansky
*/
@SuppressWarnings("unchecked")
public class CircularQueue<T> implements Queue<T> {
private Object[] queue;
private int head;
private int tail;
private int size;
public CircularQueue(int size) {
this.size = size;
this.queue = new Object[size];
}
public void put(T element) {
queue[tail % size] = element;
tail = (tail + 1) % size;
}
public T take() {
try {
if (isEmpty()) throw new RuntimeException("The queue is empty");
return (T) queue[head];
} finally {
queue[head] = null;
head = (head + 1) % size;
}
}
public boolean isEmpty() {
return tail - head == 0;
}
@Override
public String toString() {
return "CircularQueue=" + Arrays.toString(queue);
}
}
package com.hackerrank.challenges;
/**
* @author Alexander Krasniansky
*/
public interface Queue<T> {
void put(T element);
T take();
boolean isEmpty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment