Repository navigation
Expand file tree
/
Copy pathLinkedList.java
More file actions
97 lines (82 loc) · 1.91 KB
/
Copy pathLinkedList.java
File metadata and controls
97 lines (82 loc) · 1.91 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
public class LinkedList {
private Node first;
private Node last;
private class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
}
public void addFirst(int item) {
Node node = new Node(item);
if (isEmpty()) {
first = last = node;
} else {
node.next = first;
first = node;
}
}
public void addLast(int item) {
Node node = new Node(item);
if (isEmpty()) {
first = last = node;
} else {
last.next = node;
last = node;
}
}
private boolean isEmpty() {
return first == null;
}
public int indexOf(int item) {
Node node = first;
int index = 0;
while (node != null) {
if (node.value == item) {
return index;
}
node = node.next;
index++;
}
return -1;
}
public void deleteFirst() {
if (isEmpty()) {
return;
}
if (first == last) {
first = last = null;
} else {
first = first.next;
}
}
public void deleteLast() {
Node node = first;
if (isEmpty()) {
return;
}
if (first == last) {
first = last = null;
} else {
while (node != last) {
if (node.next == last) {
node.next = null;
last = node;
} else {
node = node.next;
}
}
}
}
public boolean contains(int item) {
Node node = first;
while (node != null) {
if (node.value == item) {
return true;
}
node = node.next;
}
return false;
}
}