Answer the question
In order to leave comments, you need to log in
How to implement the poll method in one loop?
There is a queue implementation based on two stacks, I use two cycles, the first shifts elements from one stack to another until it reaches the last one, remembers it, deletes it and returns it, then the elements are shifted back for further operations.
How to make the poll method have one loop?
public class SimpleQueue<T> {
int count = 0;
private final SimpleStack<T> in = new SimpleStack<>();
private final SimpleStack<T> out = new SimpleStack<>();
/*
* Метод poll() - должен возвращать первое значение и удалять его из коллекции.
*/
public T poll() {
for (int i = 0; i < count - 1; i++) {
in.push(out.pop());
}
count--;
T rsl = out.pop();
for (int i = 0; i < count; i++) {
out.push(in.pop());
}
return rsl;
}
Answer the question
In order to leave comments, you need to log in
The canonical implementation does not shift anything back.
Your names are strange, I would change them.
enqueue should lie in in
poll should shift from in to out as long as in is not empty. out.push(in.pop())
the result of poll will be out.pop()
public void enqueue(T value){
in.push(value);
}
public T poll() {
while(!in.isEmpty()) {
out.push(in.pop());
}
if (out.isEmpty()) throw new NoSuchElementException();
return out.pop();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question