Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

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