BikeStorage.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. public class BikeStorage {
  2. private Node head;
  3. /**
  4. * Add a bike to the BikeStorage.
  5. *
  6. * @param bike the bike you want to add
  7. */
  8. public void add(Bike bike) {
  9. Node newNode = new Node(bike);
  10. newNode.setNext(head);
  11. head = newNode;
  12. }
  13. /**
  14. * Check if bike is in the BikeStorage
  15. *
  16. * @param bike the bike you want to search
  17. * @return the bike, if you found it, otherwise {@code null}
  18. */
  19. public boolean contains(Bike bike) {
  20. // Normalerweise würde man hier nach einer Seriennummer
  21. // oder ähnlichem - also "identifizierenden" Attributen
  22. // von Bike - suchen und dann das gesamte Bike zurückgeben
  23. Node currentNode = head;
  24. // usually you you should implement .equals(),
  25. // and not use != or == for objects
  26. while (currentNode != null && currentNode.getElement() != bike) {
  27. currentNode = currentNode.getNext();
  28. }
  29. return currentNode != null;
  30. }
  31. /**
  32. * Get a bike.
  33. *
  34. * @param bike the bike you want to get
  35. * @return
  36. */
  37. public Bike get(Bike bike) {
  38. if (contains(bike)) {
  39. Node currentNode = head;
  40. while (currentNode.getElement() != bike) {
  41. currentNode = currentNode.getNext();
  42. }
  43. return bike;
  44. } else {
  45. return null;
  46. }
  47. }
  48. /**
  49. * Remove bike from the BikeStorage, if it exists.
  50. *
  51. * @param bike the bike you want to search
  52. * @return {@code bike} if it is in BikeStorage, otherwise {@code null}
  53. */
  54. public Bike remove(Bike bike) {
  55. if (!contains(bike)) {
  56. return null;
  57. } else if (head.getElement() == bike) {
  58. head = head.getNext();
  59. return bike;
  60. } else {
  61. // Knoten und Vorgängerknoten finden
  62. Node previousNode = head;
  63. Node currentNode = head;
  64. while (currentNode.getElement() != bike) {
  65. previousNode = currentNode;
  66. currentNode = currentNode.getNext();
  67. }
  68. // Zeiger umbiegen
  69. previousNode.setNext(currentNode.getNext());
  70. return bike;
  71. }
  72. }
  73. /**
  74. * Print all bikes in BikeStorage.
  75. */
  76. public void printBikes() {
  77. Node currentNode = head;
  78. System.out.print("start -> ");
  79. while (currentNode != null) {
  80. System.out.print(currentNode);
  81. System.out.print(" -> ");
  82. currentNode = currentNode.getNext();
  83. }
  84. System.out.println("null");
  85. }
  86. }