Linked list>
— , , , , ( ) , , .
Not all industrial languages have built-in support for linked list as data structures. However, it is not difficult to implement it yourself as a class or structure. For comfortable work with relevant algorithms, we will add built-in bidirectional linked lists already in the basic definition of the Hi language.
First, let's create an instance of our experimental list:
VAR list = <"I", "will", "be">
In the example above, bidirectional links are automatically created for three nodes.
A linked non-empty list in Hi always has one node that is current or "active". By default, this is the last added element, which is now "be". Let's check this:
PRINT list.current # "be"
Let's add two more elements to our list:
list.insert "back", "!" # list : "I", "will", "be", "back", "!"
The built-in insert method adds new elements immediately after the active node, automatically builds new links and makes the last added element current (you can add and make the first a new list node using the insertFirst method).
Deletion is carried out in a similar way for the current element:
list.remove 1 # list : "I", "will", "be", "back"
However, you can delete several elements at once, for this you must first set the pointer to the first node to be deleted :
VAR secList = list
secList.prev 2
secList.remove 2 # secList : "I", "back"
In this case, the previous node before the deleted one becomes the current one. If the first element of the list is deleted, the new first element becomes the current one .
You can replace the current node with another simply by assigning a new value to the element:
secList.urrent = "smile" # secList : "smile ", "back"
You can delete all nodes, that is, you can make the list empty like this:
secList = <>
It is convenient to go to the first and last nodes as follows:
list.first
LET last = list.last #
Thus, you can easily perform various operations with the list:
PRINT list # "I", "will", "be", "back"
list.first
list.next
list.insert "not"
LET be = list