/*******************************************************************
* 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>();
/***************************************************************
* Statement:
* Indicate whether the queue is empty.
*
* Time Complexity of Solution:
* Best = Average = Worst = const.
*
* Technical Details: The queue is empty precisely when both the
* input stack and the output stack are empty.
*
* Note that the input stack may occasionally be empty
* while the output stack is not empty; vice versa.
*
*****************************************************************/
public boolean isEmpty() {
return input.isEmpty() && output.isEmpty();
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class QueueWithStackTest {
/**
* Test of isEmpty method, of class QueueWithStack.
*/
@Test
public void testIsEmpty() {
System.out.println("isEmpty");
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());
}
}