Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 300
Expand file tree
/
Copy pathLinkedList.java
More file actions
Latest commit
108 lines (92 loc) · 2.48 KB
/
Copy pathLinkedList.java
File metadata and controls
108 lines (92 loc) · 2.48 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
98
99
100
101
102
103
104
105
106
107
108
publicclassLinkedList<T> {
publicstaticvoidmain(String[] args) {
LinkedList<String> list = newLinkedList<>("head");
list.add("second");
list.add("third");
list.add("last");
System.out.println(list.length()); // should be 4
System.out.println(list.remove("third")); // should print "third"
System.out.println(list.length()); // should be 3
}
privateNode<T> head;
publicLinkedList(Thead) {
this.head = newNode<T>(head);
}
publicLinkedList() {
}
/**
* Adds a value to the end of the list
*
* @param val value to be added
* @return true if add succeeds; false otherwise
*/
publicbooleanadd(Tval) {
Node<T> tmp = this.head;
if (tmp == null) {
this.head = newNode<T>(val);
returntrue;
}
while (tmp.next() != null) {
tmp = tmp.next();
}
tmp.setNext(newNode<T>(val));
returntrue;
}
/**
* Returns the value that was removed if the requested value
* was found. Otherwise returns null if the value doesn't exist
* in the list
*
* @param val
* @return T
*/
publicTremove(Tval) {
if (this.head != null) {
if (this.head.getValue() == val) {
Node<T> trash = this.head;
this.head = this.head.next();
trash.setNext(null);
returntrash.getValue();
}
} else {
returnnull;
}
Node<T> prev = this.head;
Node<T> tmp = prev.next();
while (tmp != null) {
if (tmp.getValue() == val) {
prev.setNext(tmp.next());
tmp.setNext(null);
returntmp.getValue();
}
tmp = tmp.next();
prev = prev.next();
}
returnnull;
}
publicintlength() {
intlen = 0;
Node<T> tmp = this.head;
while (tmp != null) {
len++;
tmp = tmp.next();
}
returnlen;
}
privateclassNode<T> {
privateNode<T> nextNode;
privateTvalue;
publicNode(Tval) {
this.value = val;
}
publicNode<T> next() {
returnthis.nextNode;
}
publicvoidsetNext(Node<T> next) {
this.nextNode = next;
}
publicTgetValue() {
returnthis.value;
}
}
}