7.9 The Sorted Linked ListThe items in a linked list can be sorted in ascending or descending order as was done with a sequence. Consider the sorted linked list illustrated in Figure 7.9.1. The sorted list has to be created and maintained as items are added and removed. Linear SearchThe linear search for use with the linked list can be modified to take advantage of the sorted items. The only change required is to add a second condition that terminates the loop early if we encounter a value larger than the target. The search routine for a sorted linked list is shown in the listing below. Program Listing
Inserting NodesAdding a new node to an unsorted linked list is simple because we can simply add it to the front or end of the list since its placement is not important. When adding a node to a sorted list, however, the correct position for the new value must be found and the new node linked into the list at that position. The Python implementation for inserting a value into a sorted linked list is provided below. Program Listing
As with the removal operation for the unsorted list, we must position two temporary external references by traversing through the linked list searching for the correct position of the new value. The only difference is the loop termination condition. To insert a new node, we must terminate the loop upon finding the first value larger than the new value being added. Three cases can occur when inserting a node into a sorted linked list, as illustrated in Figure 7.9.2: the node is inserted in the front, at the end, or somewhere in the middle. After finding the correct position, a new node is created and its After linking the new node to the list, we must determine if it is being inserted at the front of the list, in which case the Traversing and DeletingThe traversal operation implemented for the unsorted linked list can be used with both sorted and unsorted linked lists since it is not dependent on the contents of the list itself. Deleting from a sorted linked list is the same operation used with an unsorted list with one exception. Searching for the node containing the target value can end early after encountering the first value larger than the one to be deleted.
|