Data Structures — Unit 1 — Pointers and Linked Lists (cont. again)

Linked structures without pointers

You don't need dynamic allocation and the heap to use linked structures.

This is useful if you are using a language that does not support heap operations (e.g. FORTRAN-77, or assembly language).

It is also useful if you can predictability is of paramount importance.

Declarations:

typedef int NodeNum ;
static const int NULLNODE = -1 ;

struct Node {
    SomeType data ;
    NodeNum next ;
} ;

const int numberOfNodes = 2048 ;

Node nd[ numberOfNodes ] ; // Big array of nodes.
NodeNum freeList = NULLNODE; // number of first free node

void newNode(NodeNum &num ) {
    // Allocate the first node on the free list.
    num = freeList ;
    if( freeList != NULLNODE ) {
        freeList = nd[freeList].next ; } }

void delNode(NodeNum num) {
    // Add the node to the free list
    nd[num].next = freeList ;
    freeList = num ; }

void initNodes() {
    // Initially, all nodes should be on the free list.
    for(NodeNum i = 0 ; i < numberOfNodes; ++i ) {
    delNode(i) ; } }

One disadvantage is that the space used for these nodes can not shared with the space used for other type.

Can still use pointer to link method, only now it uses a pointer to an integer.

One can also declare the next field to be a pointer, but do all allocation and deallocation in the array rather than by new and delete.

Problem: If SomeType is a class, then the con- and destructors won't be called as appropriate.

Exercise: Modify this so that constructors and destructors are called as appropriate.

Other varieties of linked lists.

We have focussed on singly linked lists.

Some variations:

Summary


© Theodore S. Norvell 1996--2004.