/*******************************************************************
* Author: Isai Damier
* Title: QueueWithStack
* Project: geekviewpoint
* Package: datastructure
*
* Description: To implement a Queue using Stack datastructure,
* two stacks are sufficient: a stack for enqueuing and a stack
* for dequeuing. Recall that stacks are LIFO objects (i.e. Last
* In First Out), whereas queues are normally FIFO objects (i.e.
* First In First Out). Hence although adding elements to a stack
* is similar to adding elements to a queue, the removal process
* for each datastructure is different.
*
* Notice how in the following implementation queue.enqueue() is
* the same as stack.push(). However, two stacks are used for
* proper dequeuing.
******************************************************************/
import java.util.Stack;
public class QueueWithStack<E> {
private final Stack<E> input = new Stack<E>();
private final Stack<E> output = new Stack<E>();
/***************************************************************
* Description: Clear the queue.
*
* Technical Details: The queue is cleared precisely when both the
* input stack and the output stack are cleared.
*
****************************************************************/
public void clear() {
input.clear();
output.clear();
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class QueueWithStackTest {
/**
* Test of clear method, of class QueueWithStack.
*/
@Test
public void testClear() {
System.out.println("clear");
QueueWithStack<Integer> queue = new QueueWithStack<Integer>();
Integer[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
assertTrue(queue.isEmpty());
assertEquals(0, queue.size());
for (int d : data) {
queue.enqueue(d);
}
assertFalse(queue.isEmpty());
assertEquals(data.length, queue.size());
queue.clear();
assertTrue(queue.isEmpty());
assertEquals(0, queue.size());
}
}