Created
July 3, 2013 15:20
-
-
Save PetrGlad/5919258 to your computer and use it in GitHub Desktop.
Yet another interview task: Linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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