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.
We have focussed on singly linked lists.
Some variations:
We can put a special node at the start of the list that contains no data.
The empty list has one node.
This way one is always inserting after some node, which eliminates the need for pointers to links
Sometimes the tail pointer is made to point back to the start of the list.
One difficulty with singly linked lists is that it is more difficult to traverse them backwards than it is to traverse them forward.
Doubly linked lists solve this problem by using pointers that point to the previous node
These techniques can be combined in all possible ways.
For example, we could have a circular, doubly linked list with a dummy node.
© Theodore S. Norvell 1996--2004.