-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWS3.java
69 lines (60 loc) · 2.01 KB
/
WS3.java
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
public class Worksheet3 {
public static int max(Node<Integer> node) {
if (node == null) {
return 0;
}
Node<Integer> current = node;
int maxVal = node.data;
while (current != null) {
if (current.data > maxVal) {
maxVal = current.data;
}
current = current.next;
}
return maxVal;
};
public static int maxRecursive(Node<Integer> node) {
if (node == null) {
return 0;
}
int maxVal = node.data;
if (node.next != null) {
int nextMax = maxRecursive(node.next);
if (nextMax > maxVal) {
maxVal = nextMax;
}
}
return maxVal;
}
public static void remove(LinkedList<String> list, String key) {
if (list == null || key == null) {
return;
}
Node<String> curr = list.getHead();
while (list.getHead() != null && list.getHead().data.equals(key)) {
list.setHead(list.getHead().next);
}
while (curr != null && curr.next != null) {
if (curr.next.data.equals(key)) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("one");
list.add("two");
list.add("three");
// Using the iterator to traverse the list
LinkedList<String>.LinkedListIterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
iterator = list.iterator(); // Reset the iterator
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}