-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedLinkedList.java
More file actions
49 lines (43 loc) · 1.09 KB
/
SortedLinkedList.java
File metadata and controls
49 lines (43 loc) · 1.09 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
package list;
public class SortedLinkedList<T extends Comparable<T>> {
private Node<T> head;
public void insert(T data) {
Node<T> newNode = new Node<T>(data);
if (this.head == null || this.head.getData().compareTo(data) > 0) {
newNode.setNextNode(this.head);
this.head = newNode;
return;
}
Node<T> current = this.head;
while (current != null && current.getNextNode() != null
&& current.getNextNode().getData().compareTo(data) < 0) {
current = current.getNextNode();
}
newNode.setNextNode(current.getNextNode());
current.setNextNode(newNode);
}
public Node<T> getHead() {
return this.head;
}
@Override
public String toString() {
String result = "[";
Node<T> current = this.head;
while (current != null) {
result += current.toString() + ", ";
current = current.getNextNode();
}
result += "]";
return result;
}
public static void main(String[] args) {
SortedLinkedList<Integer> sll = new SortedLinkedList<Integer>();
sll.insert(6);
sll.insert(4);
sll.insert(2);
sll.insert(8);
sll.insert(3);
sll.insert(5);
System.out.println(sll);
}
}