A particularly useful kind of linked list is one that is sorted. In this tutorial, you will learn about linked lists by writing a method to insert elements into a sorted linked list.
We first need the definition of a class for constructing nodes of the linked list:
class Node { int key; Node link; }We can now create objects of class Node to construct our linked list. Note that key does not necessarily need to be an integer. We use integers here for simplicity. A node might contain other members depending on the purpose of the linked list.
Now before we can design an insertion method, we must think about what it means to insert an element into a linked list. In other words we need the specifications for insert.
Here is the header for the linked list class and the insert method.
public class LinkedList { Node head; public insert(int key) { Node current = head; // The rest of the method will go here. } }
We are going to use the local variable current to keep track of where we are in the list.
What Java statement lets us advance current from one node in the list to the next?
We will use a while loop to advance current repeatedly, thus traversing the whole list.
while( /* condition */ ) { // body of the loop }
What condition will be true while we are traversing the list and false when we get to the end of the list?
When you have answered the two questions above, you may proceed to the next step.