Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.

See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
// by Galileo, 02/2022
 
FIL = 1 : DATO = 2 : LINK = 3
countNodes = 0 : Nodes = 10
 
dim list(Nodes, 3)
 
 
sub searchNode(node)
    local i, prevNode
 
    for i = 1 to countNodes
        if i = node break
        prevNode = list(prevNode, LINK)
    next
 
    return prevNode
end sub
 
sub insertNode(node, newNode, after)
    local prevNode, i
 
    prevNode = searchNode(node)
 
    if after prevNode = list(prevNode, LINK)
 
    for i = 1 to Nodes
        if not list(i, FIL) break
    next
 
    list(i, FIL) = true
    list(i, DATO) = newNode
    list(i, LINK) = list(prevNode, LINK)
    list(prevNode, LINK) = i
 
    countNodes = countNodes + 1
    if countNodes = Nodes then Nodes = Nodes + 10 : redim list(Nodes, 3) : end if
end sub
 
 
sub printNode(node)
    local prevNode
 
    prevNode = searchNode(node)
    node = list(prevNode, LINK)
 
    // print list(node, FIL);
    print list(node, DATO);
    // print list(node, LINK);
    print
end sub
 
 
insertNode(1, 1000, true)
insertNode(1, 2000, true)
insertNode(1, 3000, true)
 
printNode(1)
printNode(2)
printNode(3)