Java Code to Insert an Item in a Sorted List
Java Code to Insert an Item in a Sorted List
To insert an item in a sorted list, the algorithm must first search through the list until it finds the appropriate place to put the item: this is just before the first item that’s larger, as shown in Figure 5.12.
214 CHAPTER 5 Linked Lists
FIGURE 5.12
A newly inserted link.
When the algorithm finds where to put it, the item can be inserted in the usual way by changing next in the new link to point to the next link and changing next in the previous link to point to the new link. However, we need to consider some special cases: The link might need to be inserted at the beginning of the list, or it might need to go at the end. Let’s look at the code:
public void insert(long key) // insert in order { Link newLink = new Link(key); // make new link Link previous = null; // start at first Link current = first;
// until end of list, while(current != null && key > current.dData) { // or key > current, previous = current; current = current.next; // go to next item }
if(previous==null) // at beginning of list
first = newLink; // first --> newLink else // not at beginning previous.next = newLink; // old prev --> newLink newLink.next = current; // newLink --> old current } // end insert()
We need to maintain a previous reference as we move along, so we can modify the previous link’s next field to point to the new link. After creating the new link, we
Sorted Lists 215
prepare to search for the insertion point by setting current to first in the usual way. We also set previous to null ; this step is important because later we’ll use this null value to determine whether we’re still at the beginning of the list.
The while loop is similar to those we’ve used before to search for the insertion point, but there’s an added condition. The loop terminates when the key of the link currently being examined ( current.dData ) is no longer smaller than the key of the link being inserted ( key ); this is the most usual case, where a key is inserted some- where in the middle of the list.
However, the while loop also terminates if current is null . This happens at the end of the list (the next field of the last element is null ), or if the list is empty to begin with ( first is null ).
When the while loop terminates, then, we may be at the beginning, the middle, or the end of the list, or the list may be empty.
If we’re at the beginning, or the list is empty, previous will be null ; so we set first to the new link. Otherwise, we’re in the middle of the list, or at the end, and we set previous.next to the new link.
In any case we set the new link’s next field to current . If we’re at the end of the list, current is null , so the new link’s next field is appropriately set to this value.