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

SimpleLinkedList.java 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import java.lang.reflect.Array;
  2. import java.util.NoSuchElementException;
  3. import java.util.Objects;
  4. public class SimpleLinkedList<T> {
  5. private static class Element<T> {
  6. final T value;
  7. Element next;
  8. Element(T value) {
  9. this.value = value;
  10. }
  11. }
  12. private Element<T> head;
  13. private int size;
  14. public SimpleLinkedList() {
  15. }
  16. public SimpleLinkedList(T[] values) {
  17. for (int ii = values.length - 1; ii >= 0; ii--) {
  18. push(values[ii]);
  19. }
  20. }
  21. public final void push(T value) {
  22. Element<T> newElement = new Element<>(value);
  23. this.size++;
  24. if (Objects.isNull(head)) {
  25. head = newElement;
  26. } else {
  27. newElement.next = head;
  28. head = newElement;
  29. }
  30. }
  31. public T pop() {
  32. if (Objects.isNull(head)) {
  33. throw new NoSuchElementException();
  34. }
  35. T value = head.value;
  36. head = head.next;
  37. this.size--;
  38. return value;
  39. }
  40. public void reverse() {
  41. Element<T> current = head;
  42. Element<T> next;
  43. Element<T> previous = null;
  44. while (Objects.nonNull(current)) {
  45. next = current.next;
  46. current.next = previous;
  47. previous = current;
  48. current = next;
  49. }
  50. head = previous;
  51. }
  52. public T[] asArray(Class<T> clazz) {
  53. T[] result = newArray(clazz, this.size);
  54. int index = 0;
  55. Element<T> current = head;
  56. while (Objects.nonNull(current)) {
  57. result[index++] = current.value;
  58. current = current.next;
  59. }
  60. return result;
  61. }
  62. private <T> T[] newArray(Class<T> clazz, int size) {
  63. @SuppressWarnings("unchecked")
  64. T[] arr = (T[]) Array.newInstance(clazz, size);
  65. return arr;
  66. }
  67. public int size() {
  68. return this.size;
  69. }
  70. }