В соответствии с моей реализацией у меня есть {1, 2, 3, 8}.
Прикреплен мой код:
Код: Выделить всё
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
/**
* A Strictly Monotonic increasing Queue. [1, 2, 3, 6, 8, 12, 16, 23]. Where the largest element is
* at the back of the Queue (tail of the linkedList).
* Adapter Design Pattern.
*/
public class MonotonicQueue implements Iterable {
private final Deque queue;
private int t = 0; // Number of elements in the Queue
public MonotonicQueue() {
this.queue = new LinkedList();
}
private void nullChecker(E obj) {
if (obj == null)
throw new NullPointerException();
}
public int size() {
return t;
}
public boolean isEmpty() {
return queue.isEmpty();
}
public void push(E obj) {
nullChecker(obj);
if (isEmpty())
queue.offerFirst(obj);
else {
while(!queue.isEmpty() && queue.peekLast().compareTo(obj) >= 0) {
queue.pollLast();
t--;
}
queue.offerLast(obj);
}
t++;
}
public E pop() throws EmptyQueueException {
if (isEmpty())
throw new EmptyQueueException();
t--;
return queue.pop(); // This will return the maximum element (The front element) in the Queue
}
public boolean contains(E obj) {
if (obj == null)
return false;
if (isEmpty())
return false;
// If obj > the element at the front of the Queue, then the Queue cannot contain obj.
else if (obj.compareTo(queue.peekLast()) > 0)
return false;
else {
for (E data : this) {
if (data.compareTo(obj) == 0)
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("[");
Iterator iter = this.iterator();
while (iter.hasNext()) {
stringBuilder.append(iter.next());
if (iter.hasNext())
stringBuilder.append("--> ");
}
stringBuilder.append("]");
return stringBuilder.toString();
}
@Override
public Iterator iterator() {
return queue.iterator();
}
}
Подробнее здесь: https://stackoverflow.com/questions/718 ... sing-queue