Created
January 3, 2017 00:21
-
-
Save Krasnyanskiy/b8e192a593d4505686e4c5d4c4448f77 to your computer and use it in GitHub Desktop.
-java: queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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