lots of exercises in java... from https://github.com/exercism/java

DoublyLinkedList.java 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. public final class DoublyLinkedList<T> {
  2. private Element<T> head;
  3. public void push(T value) {
  4. if (head == null) {
  5. head = new Element<>(value, null, null);
  6. head.next = head;
  7. head.prev = head;
  8. return;
  9. }
  10. Element<T> oldTail = head.prev;
  11. Element<T> tail = new Element<>(value, oldTail, head);
  12. oldTail.next = tail;
  13. head.prev = tail;
  14. }
  15. public T pop() {
  16. head = head.prev;
  17. return shift();
  18. }
  19. public void unshift(T value) {
  20. push(value);
  21. head = head.prev;
  22. }
  23. public T shift() {
  24. T value = head.value;
  25. Element<T> newHead = head.next;
  26. Element<T> newTail = head.prev;
  27. if (newHead == head) {
  28. head = null;
  29. }
  30. else {
  31. newHead.prev = newTail;
  32. newTail.next = newHead;
  33. head = newHead;
  34. }
  35. return value;
  36. }
  37. private static final class Element<T> {
  38. private final T value;
  39. private Element<T> prev;
  40. private Element<T> next;
  41. public Element(T value, Element<T> prev, Element<T> next) {
  42. this.value = value;
  43. this.prev = prev;
  44. this.next = next;
  45. }
  46. }
  47. }