Skip to content

Instantly share code, notes, and snippets.

@PetrGlad
Created July 3, 2013 15:20
Show Gist options
  • Save PetrGlad/5919258 to your computer and use it in GitHub Desktop.
Save PetrGlad/5919258 to your computer and use it in GitHub Desktop.
Yet another interview task: Linked list
package lab;
public class LinkedList<T> {
class Node {
public final T value;
public final Node prev;
public Node(Node prev, T value) {
this.prev = prev;
this.value = value;
}
}
Node head;
public LinkedList() {
}
public void push(T value) {
head = new Node(head, value);
}
public T pop() {
if (head == null)
throw new RuntimeException("List is empty");
T result = head.value;
head = head.prev;
return result;
}
}
package lab;
import org.junit.Assert;
import org.junit.Test;
public class LinkedListTest {
@Test
public void test() {
LinkedList<Long> linkedList = new LinkedList<Long>();
try {
linkedList.pop();
Assert.fail("Exception expected");
} catch (RuntimeException e) {
// expected
}
linkedList.push(1L);
Assert.assertEquals(new Long(1L), linkedList.pop());
linkedList.push(1L);
linkedList.push(2L);
Assert.assertEquals(new Long(2L), linkedList.pop());
Assert.assertEquals(new Long(1L), linkedList.pop());
try {
linkedList.pop();
Assert.fail("Exception expected");
} catch (RuntimeException e) {
// expected
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment