forked from NITSkmOS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.java
107 lines (91 loc) · 2.49 KB
/
linked_list.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
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
public class linked_list<T> {
public static void main(String[] args) {
linked_list<String> list = new linked_list<String>("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
}
private Node<T> head;
public linked_list(T head) {
this.head = new Node<T>(head);
}
public linked_list() {
}
/**
* Adds a value to the end of the list
*
* @param val value to be added
* @return true if add succeeds; false otherwise
*/
public boolean add(T val) {
Node<T> tmp = this.head;
if (tmp == null) {
this.head = new Node<T>(val);
return true;
}
while (tmp.next() != null) {
tmp = tmp.next();
}
tmp.setNext(new Node<T>(val));
return true;
}
/**
* 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
*/
public T remove(T val) {
if (this.head != null) {
if (this.head.getValue() == val) {
Node<T> trash = this.head;
this.head = this.head.next();
trash.setNext(null);
return trash.getValue();
}
} else {
return null;
}
Node<T> prev = this.head;
Node<T> tmp = prev.next();
while (tmp != null) {
if (tmp.getValue() == val) {
prev.setNext(tmp.next());
tmp.setNext(null);
return tmp.getValue();
}
tmp = tmp.next();
prev = prev.next();
}
return null;
}
public int length() {
int len = 0;
Node<T> tmp = this.head;
while (tmp != null) {
len++;
tmp = tmp.next();
}
return len;
}
private class Node<T> {
private Node<T> nextNode;
private T value;
public Node(T val) {
this.value = val;
}
public Node<T> next() {
return this.nextNode;
}
public void setNext(Node<T> next) {
this.nextNode = next;
}
public T getValue() {
return this.value;
}
}
}