86 lines
1.8 KiB
Java
86 lines
1.8 KiB
Java
package esercizi;
|
|
|
|
import exceptions.EmptyQueueException;
|
|
import queue.Queue;
|
|
import sequence.ArraySequence;
|
|
import stack.ArrayStack;
|
|
|
|
/**
|
|
* Created with MONSTER.
|
|
* User: xgiovio
|
|
* Date: 13/04/2014
|
|
* Time: 23:01
|
|
*/
|
|
|
|
// queue emulated via 2 stacks
|
|
|
|
public class SQueue<E> implements Queue<E> {
|
|
|
|
|
|
private ArrayStack<E> accoda = new ArrayStack<E>();
|
|
private ArrayStack<E> decoda = new ArrayStack<E>();
|
|
|
|
@Override
|
|
public void enqueue(E element) {
|
|
|
|
accoda.push(element);
|
|
|
|
}
|
|
|
|
@Override
|
|
public E dequeue() throws EmptyQueueException {
|
|
|
|
if (accoda.isEmpty()){
|
|
throw new EmptyQueueException();
|
|
} else {
|
|
|
|
E temp;
|
|
int size = accoda.size();
|
|
for (int i = 0; i <size; i++) {
|
|
decoda.push(accoda.pop());
|
|
}
|
|
temp = decoda.pop();
|
|
size = decoda.size();
|
|
for (int i = 0; i < size; i++) {
|
|
accoda.push(decoda.pop());
|
|
}
|
|
return temp;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public E front() throws EmptyQueueException {
|
|
if (accoda.isEmpty()){
|
|
throw new EmptyQueueException();
|
|
} else {
|
|
|
|
E temp;
|
|
int size = accoda.size();
|
|
for (int i = 0; i <size; i++) {
|
|
decoda.push(accoda.pop());
|
|
}
|
|
temp = decoda.top();
|
|
size = decoda.size();
|
|
for (int i = 0; i < size; i++) {
|
|
accoda.push(decoda.pop());
|
|
}
|
|
return temp;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public boolean isEmpty() {
|
|
return accoda.isEmpty();
|
|
}
|
|
|
|
@Override
|
|
public int size() {
|
|
return accoda.size();
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return accoda.toString();
|
|
}
|
|
}
|