/***************************************************************************
* Author: Isai Damier
* Title: Stack with Linked List
* Project: geekviewpoint
* Package: datastructure
*
* Description: Stack implementation using LinkedList
*
* Technical Detail:
* Java uses addFirst() instead of addToHead(). Also getFirst
* returns the head without removing it; whereas removeFirst
* deletes the head.
*
* A single LinkedList is used to implement this
* stackWithLinkedList. To implement stackWithLinkedList.push(E)
* addFirst(E) is used; for stackWithLinkedList.pop() revomeFirst()
* is used; for stackWithLinkedList.peep() getFirst() is used. The
* trick is to remove elements from the same end they are added.
*
* E is a generic that may be replaced with any actual object such
* as String or Integer or Object.
**************************************************************************/
import java.util.LinkedList;
public class StackWithLinkedList<E> {
private LinkedList<E> list = new LinkedList<E>();
public E pop() {
return list.removeFirst();
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class StackWithLinkedListTest {
/**
* Test of pop method, of class StackWithLinkedList.
*/
@Test
public void testPop() {
System.out.println("pop");
StackWithLinkedList<Integer> stackWithLinkedList =
new StackWithLinkedList<Integer>();
Integer[] inputs = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i : inputs) {
stackWithLinkedList.push(i);
}
assertFalse(stackWithLinkedList.isEmpty());
assertEquals(inputs.length, stackWithLinkedList.size());
for (int i = inputs.length - 1; i >= 0; i--) {
assertEquals(inputs[i], stackWithLinkedList.pop());
}
assertTrue(stackWithLinkedList.isEmpty());
assertEquals(0, stackWithLinkedList.size());
}
}