| JavaScript Data Structures - The Linked List |
| Written by Ian Elliot | |||||
| Thursday, 05 September 2019 | |||||
Page 3 of 4
Insert AfterAnother very common list operation is to insert a new element or indeed a complete list into an existing list. For data structures such as an array inserting data involves moving a block of data to free up some space for the items being inserted. In a linked list you don't have to do this because all you have to do is change some links. For example to insert x into the list
after B all you have to do is create x and point it at what B was pointing at and set B to point at x:
This is fairly easy to program as long as you remember to keep the end pointer correct. For example a method that inserts a new item of data following a node which stores a specified item of data is just:
Notice that you only have to fix up the end pointer when the item is inserted at the end and you don't have to fix the start pointer because this method can't insert something before the first node. IndexingWhere the linked list suffers is when you need to refer to nodes by an index value. That is when you want to pretend that a linked list is an array. The only way of retrieving say the fifth element in the list is to traverse the list and stop at the fifth element. There are many ways to keep a count of how many elements you have retrieved, here is just one:
You could also use a for loop but if so you would need to check that the index was in the range of the list or include a test for the end of the list. Notice that this indexing routing returns the entire node and not just the data. In most cases it would probably be better to return the data but then you would need an item get and an item set method. EachAs a final example a useful method and one that is in line with functional thinking is the each method which applies a function to each element of the list.
For example you could use this to display the entire list using an alert function: list.each(function(item) {alert(item.data); }); |
|||||
| Last Updated ( Thursday, 05 September 2019 ) |
