Reputation: 45
I am currently writing a program that inserts strings into a linked list but when it inserts the strings, it sorts them alphabetically (using the compareTo method). I am trying to cover all the possible boundaries and am currently stuck on how to insert a new node if it is to go at the beginning of the list (thus, the variable previous is null). This is what I have so far:
public class LinkedList{
private Node root;
private Node tail;
public void add(String data){
Node current = root;
Node previous = null;
Node newNode = new Node(data);
if(root == null){
root = newNode;
tail = root;
newNode.next = null;
return;
}
for( ; current != null; previous = current, current = current.next){
if(newNode.data.compareTo(current.data)<= 0){
break;
}
}
if(previous != null){
newNode.next = current;
previous.next = newNode;
if(current == null) {
tail = newNode;
}
} else{
// if Previous IS null
previous = newNode; //The code that does not work as expected
newNode.next = current;
}
}
public static final void main(String[] args){
LinkedList list = new LinkedList();
// for(int i = 0; i < 10; i++){
// list.add("Item");
// }
list.add("Item1");
list.add("Item2");
list.add("Item4");
System.out.println(list.toString());
list.add("Item3");
System.out.println(list.toString());
list.add("Item3");
System.out.println(list.toString());
list.add("Item0");
System.out.println(list.toString());
}
}
Upvotes: 1
Views: 336
Reputation: 905
You just have to insert the node:
else{
// if Previous IS null
newNode.next = root;
root=newNode;
}
Upvotes: 4