66 lines
1.3 KiB
Java
66 lines
1.3 KiB
Java
package esercizi;
|
|
|
|
import exceptions.EmptyStackException;
|
|
import queue.NodeQueue;
|
|
import stack.Stack;
|
|
|
|
/**
|
|
* Created with MONSTER.
|
|
* User: xgiovio
|
|
* Date: 13/04/2014
|
|
* Time: 23:48
|
|
*/
|
|
|
|
// emulate a stack with a queue
|
|
public class QStack<E> implements Stack<E> {
|
|
|
|
NodeQueue<E> a = new NodeQueue<E>();
|
|
|
|
@Override
|
|
public void push(E element) {
|
|
a.enqueue(element);
|
|
}
|
|
|
|
@Override
|
|
public E top() throws EmptyStackException {
|
|
if (a.isEmpty()){
|
|
throw new EmptyStackException();
|
|
}else {
|
|
E t;
|
|
for (int i = 0 ;i<a.size() - 1;i++){
|
|
a.enqueue(a.dequeue());
|
|
}
|
|
t = a.front();
|
|
a.enqueue(a.dequeue());
|
|
return t;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public E pop() throws EmptyStackException {
|
|
if (a.isEmpty()){
|
|
throw new EmptyStackException();
|
|
}else {
|
|
for (int i = 0 ;i<a.size() - 1;i++){
|
|
a.enqueue(a.dequeue());
|
|
}
|
|
return a.dequeue();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public boolean isEmpty() {
|
|
return a.isEmpty();
|
|
}
|
|
|
|
@Override
|
|
public int size() {
|
|
return a.size();
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return a.toString();
|
|
}
|
|
}
|