public class LinkedList {
Node head;
public void insert(int key) {
Node current = head;
Node previous = null;
Node temp = new Node();
temp.key = key;
temp.link = null;
while(current != null && current.key < key) {
previous = current;
current = current.link;
}
if(head == current) {
head = temp;
temp.link = current;
} else if(current == null || current.key != key){
previous.link = temp;
temp.link = current;
}
}
}
Now that you have seen how to implement insert, you are ready to try writing other linked list methods.
Exercise: Write a delete method.