📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / Programmieren-Tutorium / Tutorium-09 / SinglyLinkedList-Template / BikeStorage.java
132939 viewsLicense: OTHER
public class BikeStorage {1private Node head;23/**4* Add a bike to the BikeStorage.5*6* @param bike the bike you want to add7*/8public void add(Bike bike) {9Node newNode = new Node(bike);10newNode.setNext(head);11head = newNode;12}1314/**15* Check if bike is in the BikeStorage16*17* @param bike the bike you want to search18* @return the bike, if you found it, otherwise {@code null}19*/20public boolean contains(Bike bike) {21// Normalerweise würde man hier nach einer Seriennummer22// oder ähnlichem - also "identifizierenden" Attributen23// von Bike - suchen und dann das gesamte Bike zurückgeben24Node currentNode = head;2526// usually you you should implement .equals(),27// and not use != or == for objects28while (currentNode != null && currentNode.getElement() != bike) {29currentNode = currentNode.getNext();30}3132return currentNode != null;33}3435/**36* Get a bike.37*38* @param bike the bike you want to get39* @return40*/41public Bike get(Bike bike) {42if (contains(bike)) {43Node currentNode = head;44while (currentNode.getElement() != bike) {45currentNode = currentNode.getNext();46}47return bike;48} else {49return null;50}51}5253/**54* Remove bike from the BikeStorage, if it exists.55*56* @param bike the bike you want to search57* @return {@code bike} if it is in BikeStorage, otherwise {@code null}58*/59public Bike remove(Bike bike) {60if (!contains(bike)) {61return null;62} else if (head.getElement() == bike) {63head = head.getNext();64return bike;65} else {66// Knoten und Vorgängerknoten finden67Node previousNode = head;68Node currentNode = head;6970while (currentNode.getElement() != bike) {71previousNode = currentNode;72currentNode = currentNode.getNext();73}7475// Zeiger umbiegen76previousNode.setNext(currentNode.getNext());77return bike;78}79}8081/**82* Print all bikes in BikeStorage.83*/84public void printBikes() {85Node currentNode = head;86System.out.print("start -> ");87while (currentNode != null) {88System.out.print(currentNode);89System.out.print(" -> ");90currentNode = currentNode.getNext();91}92System.out.println("null");93}94}959697