A/AS Level Computer Science for WJEC
Of course, there is no reason why you have to put your new item at the end of the list. Imagine you want to create a linked list that is sorted in a particular order. You can easily insert a new node in the correct place by working out where you want it, adjusting the node that is currently there to point to the new node and then telling your new node to point to the next node in the list (Figures 1.14 and 1.15). Julie
Dan
Edward
Emily
Peter
Sam
e
Figure 1.14: Linked list with node to be inserted.
pl
Julie
Dan
Edward
Emily
Peter
Sam
Sa m
Figure 1.15: Inserting data into a linked list.
Removing data from a list It is also very simple to remove an item from a list. We simply need to adjust the item before it to point to the item after it. Doing this removes the node from the list and preserves the order of items.
Hash tables
A hash table has two components, a table where the actual data is stored and a mapping function (called a hash function or hash algorithm). The hash function uses the data that is going to be entered in the table to generate the location in the table where the data should be stored. In this example, we want to use a hash table to hold some names. The initial table shown below is the easy part; it looks like any other table: Index
Name
0 1 2 3 4 Next, we need to decide on our hash algorithm; let’s say that we will take the length of the name entered and divide it by the size of the table (using the modulo (MOD) operation); the remainder gives the name’s index number.
12
Š Cambridge University Press 2017 The third party copyright material that appears in this sample may still be pending clearance and may be subject to change.