fork download
  1. class DoublyLinkedList<T> {
  2. private static class Node<T> {
  3.  
  4. private T element;
  5. private Node<T> prev;
  6. private Node<T> next;
  7.  
  8. private Node(T element, Node<T> prev, Node<T> next) {
  9. this.element = element;
  10. this.prev = prev;
  11. this.next = next;
  12. }
  13. }
  14.  
  15. private Node<T> head;
  16. private Node<T> tail;
  17. private int listSize;
  18.  
  19. public DoublyLinkedList() {
  20. head = new Node<T>(null, null, null);
  21. tail = new Node<T>(null, head, null);
  22. head.next = tail;
  23. }
  24.  
  25. public void addFirst(T element) {
  26. addBetween(element, head, head.next);
  27. }
  28.  
  29. public void addLast(T element) {
  30. addBetween(element, tail.prev, tail);
  31. }
  32.  
  33. public void addBetween(T element, Node<T> nodeBefore, Node<T> nodeAfter) {
  34.  
  35. Node<T> newNode = new Node<T>(element, nodeBefore, nodeAfter);
  36.  
  37. nodeBefore.next = newNode;
  38. nodeAfter.prev = newNode;
  39.  
  40. listSize++;
  41. }
  42.  
  43. public void reverse() {
  44. Node<T> current = head.next;
  45. Node<T> temp = null;
  46.  
  47. tail = head;
  48.  
  49. while(current != null) {
  50.  
  51. temp = current.prev;
  52.  
  53. current.prev = current.next;
  54.  
  55. current.next = temp;
  56.  
  57. current = current.prev;
  58. }
  59.  
  60. head = temp.prev;
  61. }
  62.  
  63. public static void main(String[] args) {
  64.  
  65. DoublyLinkedList<Integer> DLL = new DoublyLinkedList<Integer>();
  66. DLL.addFirst(5);
  67. DLL.addLast(6);
  68.  
  69. DLL.reverse();
  70.  
  71. DLL.addFirst(7);
  72. DLL.addFirst(8);
  73. DLL.addFirst(9);
  74. DLL.addFirst(10);
  75. System.out.println("This works.");
  76. DLL.addLast(0);
  77. System.out.println("This doesn't.");
  78.  
  79. }
  80.  
  81. }
  82.  
Runtime error #stdin #stdout #stderr 0.11s 320576KB
stdin
Standard input is empty
stdout
This works.
stderr
Exception in thread "main" java.lang.NullPointerException
	at DoublyLinkedList$Node.access$102(Main.java:2)
	at DoublyLinkedList.addBetween(Main.java:37)
	at DoublyLinkedList.addLast(Main.java:30)
	at DoublyLinkedList.main(Main.java:76)