SinglyLinkedList.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. public class SinglyLinkedList<E> {
  2. private Node<E> head;
  3. /**
  4. * Add an object to the list.
  5. *
  6. * @param object the element you want to add
  7. */
  8. public void add(E object) {
  9. Node<E> newNode = new Node<E>(object);
  10. newNode.setNext(head);
  11. head = newNode;
  12. }
  13. /**
  14. * Check if object is in is in the SinglyLinkedList
  15. *
  16. * @param object the object you want to search
  17. * @return the bike, if you found it, otherwise {@code null}
  18. */
  19. public boolean contains(E object) {
  20. Node<E> currentNode = head;
  21. while (currentNode != null && currentNode.getElement().equals(object)) {
  22. currentNode = currentNode.getNext();
  23. }
  24. return currentNode != null;
  25. }
  26. /**
  27. * Get a bike.
  28. *
  29. * @param bike the bike you want to get
  30. * @return
  31. */
  32. public E get(E bike) {
  33. if (contains(bike)) {
  34. Node<E> currentNode = head;
  35. while (currentNode.getElement() != bike) {
  36. currentNode = currentNode.getNext();
  37. }
  38. return bike;
  39. } else {
  40. return null;
  41. }
  42. }
  43. /**
  44. * Remove bike from the SinglyLinkedList, if it exists.
  45. *
  46. * @param bike the bike you want to search
  47. * @return {@code bike} if it is in SinglyLinkedList, otherwise {@code null}
  48. */
  49. public E remove(E bike) {
  50. if (!contains(bike)) {
  51. return null;
  52. } else if (head.getElement() == bike) {
  53. head = head.getNext();
  54. return bike;
  55. } else {
  56. // Knoten und Vorgängerknoten finden
  57. Node<E> previousNode = head;
  58. Node<E> currentNode = head;
  59. while (currentNode.getElement() != bike) {
  60. previousNode = currentNode;
  61. currentNode = currentNode.getNext();
  62. }
  63. // Zeiger umbiegen
  64. previousNode.setNext(currentNode.getNext());
  65. return bike;
  66. }
  67. }
  68. /**
  69. * Print all bikes in SinglyLinkedList.
  70. */
  71. public void printBikes() {
  72. Node<E> currentNode = head;
  73. System.out.print("start -> ");
  74. while (currentNode != null) {
  75. System.out.print(currentNode);
  76. System.out.print(" -> ");
  77. currentNode = currentNode.getNext();
  78. }
  79. System.out.println("null");
  80. }
  81. }