Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Implement Queue with Limited Size of Arrays
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { QueueWithFixedArray<Integer> queue = new QueueWithFixedArray<>(5); System.out.println(queue.poll());//null queue.offer(1); queue.offer(1); queue.offer(2); queue.offer(3); queue.offer(4); queue.offer(5); queue.offer(6); System.out.println(queue.poll());//1 System.out.println(queue.poll());//1 System.out.println(queue.poll());//2 System.out.println(queue.poll());//3 System.out.println(queue.poll());//4 queue.offer(7); System.out.println("size: " + queue.size());//size:3 System.out.println(queue.poll());//5 System.out.println(queue.poll());//6 System.out.println(queue.poll());//7 System.out.println(queue.poll());//null } } class QueueWithFixedArray<T> { int arraySize, size; Object[] head, tail; int headIndex, tailIndex; int endIndex; public QueueWithFixedArray(int arraySize) { this.arraySize = arraySize; size = 0; head = tail = new Object[arraySize]; headIndex = tailIndex = 0; endIndex = arraySize - 1; } public boolean offer(T element) { tail[tailIndex++] = element; size++; if (tailIndex == endIndex) { tail[endIndex] = (Object) new Object[arraySize]; tail = (Object[]) tail[endIndex]; tailIndex = 0; } return true; } public T poll() { if (size == 0) return null; @SuppressWarnings("unchecked") T element = (T) head[headIndex++]; size--; if (headIndex == endIndex) { head = (Object[]) head[endIndex]; headIndex = 0; } return element; } public int size() { return size; } }
run
|
edit
|
history
|
help
0
Circular array Loop?
Three In A Row Solver
Ab
Le saviez-vous ?
LeetCode 121 - Best time to buy and sell stock - O(n) solution
jb12.0 threads.enums
ekse
1.6
evenloop
Java - SimpleDateFormat(ting) for XML