-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
SinglyLinkedList.java
105 lines (83 loc) · 2.05 KB
/
SinglyLinkedList.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
package dsa.list;
/**
* http://java2novice.com/data-structures-in-java/linked-list/singly-linked-list/
* @param <T>
*/
public class SinglyLinkedList<T> implements LinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int total = 0;
/**
*
* @param element
* @return
*/
@Override
public SinglyLinkedList<T> add(T element) {
Node<T> nd = new Node<>();
nd.setValue(element);
/**
* check if the list is empty
*/
if (head == null) {
//since there is only one element, both head and
//tail points to the same object.
head = nd;
tail = nd;
} else {
//set current tail next link to new node
tail.setNextRef(nd);
//set tail as newly created node
tail = nd;
}
total++;
return this;
}
public T remove(){
return deleteFront();
}
public T deleteFront() {
if (head == null) {
throw new RuntimeException("Underflow...");
}
Node<T> tmp = head;
head = tmp.getNextRef();
if (head == null) {
tail = null;
}
total--;
return tmp.getValue();
}
@Override
public int size(){
return total;
}
@Override
public boolean isEmpty(){
return total == 0;
}
private class Node<T> implements Comparable<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextRef() {
return nextRef;
}
public void setNextRef(Node<T> ref) {
this.nextRef = ref;
}
@Override
public int compareTo(T arg) {
if (arg == this.value) {
return 0;
} else {
return 1;
}
}
}
}