-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
78 lines (67 loc) · 1.81 KB
/
LinkedList.java
File metadata and controls
78 lines (67 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package lib;
import java.util.List;
import java.util.ArrayList;
class LinkedList {
private Node head;
private int size;
public LinkedList() {
this.head = null;
this.size = 0;
}
public void add(Book book) {
Node newNode = new Node(book);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}
public void remove(String title) {
if (head == null) return;
if (head.data.getTitle().equalsIgnoreCase(title)) {
head = head.next;
size--;
return;
}
Node current = head;
while (current.next != null && !current.next.data.getTitle().equalsIgnoreCase(title)) {
current = current.next;
}
if (current.next != null) {
current.next = current.next.next;
size--;
}
}
public Book find(String title) {
Node current = head;
while (current != null) {
if (current.data.getTitle().equalsIgnoreCase(title)) {
return current.data;
}
current = current.next;
}
return null;
}
public List<Book> toList() {
List<Book> list = new ArrayList<>();
Node current = head;
while (current != null) {
list.add(current.data);
current = current.next;
}
return list;
}
public int size() {
return size;
}
// Clear all elements from the linked list
public void clear() {
head = null;
size = 0;
}
}