Реализация для монотонно возрастающей очередиJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Реализация для монотонно возрастающей очереди

Сообщение Anonymous »

Я пытаюсь реализовать быструю Монотонную строго возрастающую очередь, используя интерфейс Java Deque и класс LinkedList. Предположим, у меня есть массив int {10, 7, 1, 2, 4, 3, 8}. После выполнения монотонной очереди у меня должно быть {1, 2, 3, 8} или просто {3, 8}?
В соответствии с моей реализацией у меня есть {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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»