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