
// linked node implement by array
// a list has a header node
// P. Chongstitvatana    16 oct 2009

enum
    0 NIL
enum
    10000 MAXNODE			// we have MAXNODE/2 nodes

to init_list =
    node = array MAXNODE
    freenode = 10
    endnode = MAXNODE - 2

// ---- access functions ----

// a node has two fields: head, next

to head a = node[a]
to next a = node[a+1]
to setHead a value = node[a] = value
to setNext a value = node[a+1] = value

to newNode v | a =				// a new node, value v
    a = freenode
    freenode = freenode + 2
    if freenode >= endnode
        seterror "out of memory"
    else
        setHead a v
        setNext a NIL
    a

// a header node contains node a
to newList a | b =
	b = newNode 0
	setNext b a
	b

// --------- interface -----------

to addNode a el =				// add to front of el
    setNext a (next el)
    setNext el a

to containsNode a el | p = 		//  return 0/1
    p = next el
    while and (p != NIL) ((head p) != (head a))
        p = next p
    p != NIL

to removeNode a el | p =
    p = el
    while and ((next p) != NIL) ((head next p) != (head a))
        p = next p
    if (next p) != NIL
        setNext p (next next p)

// --------- display ------------

to printList el =				// recursive style
    if el != NIL
        print head el space
        printList next el

// ---------- test -------------

to testList | i el a =
    el = newList 0				// header
    for i 1 10
        a = newNode i
        addNode a el
    printList el  nl
    a = newNode 8
    print containsNode a el  nl
    removeNode a el
    printList el  nl

//to main =
//	init_list
//	testList
