ZetCode

Modula-2 linked lists

last modified November 27, 2026 Modula-2

A linked list is a chain of nodes on the heap. Each node holds a value and a pointer to the next node, and the last node points to NIL. Unlike an array, a list has no fixed size: it grows by one node at a time, and a node can be inserted or removed without moving the others.

The pointers article built a first chain of records inline. This article turns the chain into procedures, then into a module, and adds the usual list operations. All examples are compiled with -fiso; NEW and DISPOSE use ALLOCATE and DEALLOCATE from the ISO Storage module, which has the same names as the PIM one.

Nodes and lists

A list is represented by a pointer to its first node; an empty list is NIL. The cheapest way to add a value is to put a new node in front of the first one.

nodes.mod
MODULE nodes;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Storage IMPORT ALLOCATE;

TYPE
  List = POINTER TO Node;
  Node = RECORD
    value: INTEGER;
    next: List
  END;

PROCEDURE Prepend(VAR list: List; value: INTEGER);
VAR
  p: List;
BEGIN
  NEW(p);
  p^.value := value;
  p^.next := list;
  list := p
END Prepend;

PROCEDURE Show(list: List);
BEGIN
  WriteString("[");
  WHILE list # NIL DO
    WriteInt(list^.value, 3);
    list := list^.next
  END;
  WriteString(" ]");
  WriteLn
END Show;

VAR
  numbers: List;

BEGIN
  numbers := NIL;
  Show(numbers);
  Prepend(numbers, 3);
  Prepend(numbers, 2);
  Prepend(numbers, 1);
  Show(numbers)
END nodes.

The pointer type List is declared before the record it points to, so that Node can refer to it. Prepend takes the list as a VAR parameter, because the new node becomes the first one and the caller's pointer has to change. Show gets a copy of the pointer and moves it along the chain; the caller's list is not affected. Values added in front come out in the reverse order: 3 was added first and is now last.

$ gm2 -fiso nodes.mod -o nodes
$ ./nodes
[ ]
[  1  2  3 ]

Freeing the nodes

The nodes stay on the heap until the program returns them with DISPOSE. A list is freed one node at a time, from the front.

freeing.mod
MODULE freeing;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;

TYPE
  List = POINTER TO Node;
  Node = RECORD
    value: INTEGER;
    next: List
  END;

PROCEDURE Prepend(VAR list: List; value: INTEGER);
VAR
  p: List;
BEGIN
  NEW(p);
  p^.value := value;
  p^.next := list;
  list := p
END Prepend;

PROCEDURE Length(list: List): CARDINAL;
VAR
  n: CARDINAL;
BEGIN
  n := 0;
  WHILE list # NIL DO
    INC(n);
    list := list^.next
  END;
  RETURN n
END Length;

PROCEDURE Clear(VAR list: List);
VAR
  p: List;
BEGIN
  WHILE list # NIL DO
    p := list;
    list := list^.next;
    DISPOSE(p)
  END
END Clear;

VAR
  numbers: List;
  i: INTEGER;

BEGIN
  numbers := NIL;
  FOR i := 1 TO 1000 DO
    Prepend(numbers, i)
  END;
  WriteString("nodes: "); WriteCard(Length(numbers), 0); WriteLn;
  WriteString("first: "); WriteInt(numbers^.value, 0); WriteLn;
  Clear(numbers);
  WriteString("nodes: "); WriteCard(Length(numbers), 0); WriteLn
END freeing.

Clear keeps the current node in p, moves list to the next node, and only then disposes of p: a node cannot be read after it has been freed. At the end list is NIL, so the caller's variable describes a valid, empty list. Length walks the chain and counts the nodes; a list does not know its own length unless the program stores it.

$ gm2 -fiso freeing.mod -o freeing
$ ./freeing
nodes: 1000
first: 1000
nodes: 0

A list module

The type and the four procedures are needed in every later example, so they move into a module. The definition module exports the node type in full, because the following sections write new list procedures in the client programs.

IntLists.def
DEFINITION MODULE IntLists;

TYPE
  List = POINTER TO Node;
  Node = RECORD
    value: INTEGER;
    next: List
  END;

PROCEDURE Prepend(VAR list: List; value: INTEGER);
PROCEDURE Show(list: List);
PROCEDURE Length(list: List): CARDINAL;
PROCEDURE Clear(VAR list: List);

END IntLists.

The definition shows the representation of the list. That is a deliberate choice for this article; the stacks, queues and trees article hides it behind an opaque type.

IntLists.mod
IMPLEMENTATION MODULE IntLists;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;

PROCEDURE Prepend(VAR list: List; value: INTEGER);
VAR
  p: List;
BEGIN
  NEW(p);
  p^.value := value;
  p^.next := list;
  list := p
END Prepend;

PROCEDURE Show(list: List);
BEGIN
  WriteString("[");
  WHILE list # NIL DO
    WriteInt(list^.value, 4);
    list := list^.next
  END;
  WriteString(" ]");
  WriteLn
END Show;

PROCEDURE Length(list: List): CARDINAL;
VAR
  n: CARDINAL;
BEGIN
  n := 0;
  WHILE list # NIL DO
    INC(n);
    list := list^.next
  END;
  RETURN n
END Length;

PROCEDURE Clear(VAR list: List);
VAR
  p: List;
BEGIN
  WHILE list # NIL DO
    p := list;
    list := list^.next;
    DISPOSE(p)
  END
END Clear;

END IntLists.

The implementation contains the procedures of the previous sections without changes, except that Show uses a field width of 4.

tens.mod
MODULE tens;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM IntLists IMPORT List, Prepend, Show, Length, Clear;

VAR
  numbers: List;
  i: INTEGER;

BEGIN
  numbers := NIL;
  FOR i := 10 TO 1 BY -1 DO
    Prepend(numbers, i * 10)
  END;
  Show(numbers);
  WriteString("length: "); WriteCard(Length(numbers), 0); WriteLn;
  Clear(numbers)
END tens.

The client imports the type and the procedures it needs. The module is compiled once with -c, and the object file is linked with each program.

$ gm2 -fiso -c IntLists.mod
$ gm2 -fiso tens.mod IntLists.o -o tens
$ ./tens
[  10  20  30  40  50  60  70  80  90 100 ]
length: 10

Adding at the end

To add a value at the end, the program has to find the last node, the one whose next is NIL.

tail.mod
MODULE tail;
FROM Storage IMPORT ALLOCATE;
FROM IntLists IMPORT List, Prepend, Show, Clear;

PROCEDURE Append(VAR list: List; value: INTEGER);
VAR
  p, last: List;
BEGIN
  NEW(p);
  p^.value := value;
  p^.next := NIL;
  IF list = NIL THEN
    list := p
  ELSE
    last := list;
    WHILE last^.next # NIL DO
      last := last^.next
    END;
    last^.next := p
  END
END Append;

VAR
  numbers: List;
  i: INTEGER;

BEGIN
  numbers := NIL;
  FOR i := 1 TO 5 DO
    Append(numbers, i)
  END;
  Prepend(numbers, 0);
  Append(numbers, 6);
  Show(numbers);
  Clear(numbers)
END tail.

Append needs a special case for the empty list, where the new node becomes the first one. Otherwise it walks to the last node and links the new node after it. The walk makes Append slower the longer the list is; a queue, which adds at the end all the time, keeps a second pointer to the last node instead. The new procedure uses NEW, so it imports ALLOCATE itself.

$ gm2 -fiso tail.mod IntLists.o -o tail
$ ./tail
[   0   1   2   3   4   5   6 ]

Inserting in order

A list stays sorted when each value is inserted before the first node that is not smaller than it. The insertion needs the node before that position.

ordered.mod
MODULE ordered;
FROM Storage IMPORT ALLOCATE;
FROM IntLists IMPORT List, Show, Clear;

PROCEDURE InsertSorted(VAR list: List; value: INTEGER);
VAR
  p, prev, cur: List;
BEGIN
  NEW(p);
  p^.value := value;
  prev := NIL;
  cur := list;
  WHILE (cur # NIL) AND (cur^.value < value) DO
    prev := cur;
    cur := cur^.next
  END;
  p^.next := cur;
  IF prev = NIL THEN
    list := p
  ELSE
    prev^.next := p
  END
END InsertSorted;

VAR
  numbers: List;

PROCEDURE Add(value: INTEGER);
BEGIN
  InsertSorted(numbers, value);
  Show(numbers)
END Add;

BEGIN
  numbers := NIL;
  Add(42); Add(7); Add(19); Add(3);
  Add(88); Add(19); Add(56); Add(1);
  Clear(numbers)
END ordered.

InsertSorted moves two pointers along the list: cur is the current node and prev the one before it. The loop condition relies on the short-circuit AND: cur^.value is read only when cur is not NIL. When the loop stops, the new node goes between prev and cur; if prev is still NIL, it becomes the first node. Equal values are inserted before the existing ones. No elements are moved, as they would be in an array; only two pointers change.

$ gm2 -fiso ordered.mod IntLists.o -o ordered
$ ./ordered
[  42 ]
[   7  42 ]
[   7  19  42 ]
[   3   7  19  42 ]
[   3   7  19  42  88 ]
[   3   7  19  19  42  88 ]
[   3   7  19  19  42  56  88 ]
[   1   3   7  19  19  42  56  88 ]

Removing a node

Removing a node uses the same two pointers. The node before the removed one is linked to the node after it, and the removed node is disposed of.

removing.mod
MODULE removing;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Storage IMPORT DEALLOCATE;
FROM IntLists IMPORT List, Prepend, Show, Clear;

PROCEDURE Remove(VAR list: List; value: INTEGER): BOOLEAN;
VAR
  prev, cur: List;
BEGIN
  prev := NIL;
  cur := list;
  WHILE (cur # NIL) AND (cur^.value # value) DO
    prev := cur;
    cur := cur^.next
  END;
  IF cur = NIL THEN
    RETURN FALSE
  END;
  IF prev = NIL THEN
    list := cur^.next
  ELSE
    prev^.next := cur^.next
  END;
  DISPOSE(cur);
  RETURN TRUE
END Remove;

VAR
  numbers: List;

PROCEDURE Take(value: INTEGER);
BEGIN
  WriteString("remove"); WriteInt(value, 3); WriteString(": ");
  IF Remove(numbers, value) THEN
    Show(numbers)
  ELSE
    WriteString("not found"); WriteLn
  END
END Take;

VAR
  i: INTEGER;

BEGIN
  numbers := NIL;
  FOR i := 5 TO 1 BY -1 DO
    Prepend(numbers, i)
  END;
  Show(numbers);
  Take(3); Take(1); Take(5); Take(7);
  Take(2); Take(4); Take(4);
  Clear(numbers)
END removing.

Remove reports whether it found the value. Removing the first node changes the list pointer itself, so the list is a VAR parameter. The program removes values from the middle, the front and the end, tries a missing value, and empties the list completely; the second attempt to remove 4 finds an empty list.

$ gm2 -fiso removing.mod IntLists.o -o removing
$ ./removing
[   1   2   3   4   5 ]
remove  3: [   1   2   4   5 ]
remove  1: [   2   4   5 ]
remove  5: [   2   4 ]
remove  7: not found
remove  2: [   4 ]
remove  4: [ ]
remove  4: not found

Reversing in place

A list can be reversed without creating nodes: each node is taken from the front of the list and put in front of a second list.

reverse.mod
MODULE reverse;
FROM IntLists IMPORT List, Prepend, Show, Clear;

PROCEDURE Reverse(VAR list: List);
VAR
  done, rest, p: List;
BEGIN
  done := NIL;
  rest := list;
  WHILE rest # NIL DO
    p := rest;
    rest := rest^.next;
    p^.next := done;
    done := p
  END;
  list := done
END Reverse;

VAR
  numbers: List;
  i: INTEGER;

BEGIN
  numbers := NIL;
  FOR i := 1 TO 6 DO
    Prepend(numbers, i * i)
  END;
  Show(numbers);
  Reverse(numbers);
  Show(numbers);
  Reverse(numbers);
  Show(numbers);
  Clear(numbers)
END reverse.

done holds the nodes already reversed and rest those still to be done. Each step detaches the first node of rest and links it in front of done. Only the next fields change, so the reversal needs no extra memory, and reversing twice gives the original list.

$ gm2 -fiso reverse.mod IntLists.o -o reverse
$ ./reverse
[  36  25  16   9   4   1 ]
[   1   4   9  16  25  36 ]
[  36  25  16   9   4   1 ]

Recursion over lists

A list is either empty or a node followed by a list. That definition is recursive, and many list procedures are naturally recursive too.

backwards.mod
MODULE backwards;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM IntLists IMPORT List, Prepend, Show, Clear;

PROCEDURE Sum(list: List): INTEGER;
BEGIN
  IF list = NIL THEN
    RETURN 0
  END;
  RETURN list^.value + Sum(list^.next)
END Sum;

PROCEDURE ShowBackwards(list: List);
BEGIN
  IF list # NIL THEN
    ShowBackwards(list^.next);
    WriteInt(list^.value, 4)
  END
END ShowBackwards;

VAR
  numbers: List;
  i: INTEGER;

BEGIN
  numbers := NIL;
  FOR i := 1 TO 6 DO
    Prepend(numbers, i * 5)
  END;
  Show(numbers);
  WriteString("backwards:"); ShowBackwards(numbers); WriteLn;
  WriteString("sum: "); WriteInt(Sum(numbers), 0); WriteLn;
  Clear(numbers)
END backwards.

Sum returns 0 for the empty list and adds the first value to the sum of the rest. ShowBackwards prints the rest of the list before the first value, so the values come out in the reverse order without changing the list. Each node costs one level of recursion; for very long lists the loops of the earlier sections are safer, as the recursion article shows on the stack limit.

$ gm2 -fiso backwards.mod IntLists.o -o backwards
$ ./backwards
[  30  25  20  15  10   5 ]
backwards:   5  10  15  20  25  30
sum: 105

Sharing nodes

Assigning a list copies only the pointer to the first node. Both variables then share the same nodes. A copy that owns its own nodes has to be built node by node.

sharing.mod
MODULE sharing;
FROM STextIO IMPORT WriteString;
FROM Storage IMPORT ALLOCATE;
FROM IntLists IMPORT List, Prepend, Show, Clear;

PROCEDURE Copy(list: List): List;
VAR
  first, last, p: List;
BEGIN
  first := NIL;
  last := NIL;
  WHILE list # NIL DO
    NEW(p);
    p^.value := list^.value;
    p^.next := NIL;
    IF first = NIL THEN
      first := p
    ELSE
      last^.next := p
    END;
    last := p;
    list := list^.next
  END;
  RETURN first
END Copy;

VAR
  a, b, c: List;
  i: INTEGER;

BEGIN
  a := NIL;
  FOR i := 3 TO 1 BY -1 DO
    Prepend(a, i)
  END;
  b := a;
  Prepend(b, 0);
  c := Copy(a);
  a^.value := 100;

  WriteString("a: "); Show(a);
  WriteString("b: "); Show(b);
  WriteString("c: "); Show(c);

  Clear(c);
  Clear(b);
  a := NIL
END sharing.

After b := a, Prepend(b, 0) adds a node in front of the shared nodes; a still starts at 1. Changing the first value through a is then visible in b too, because it is the same node. Copy creates a new node for every value, appending through a last pointer, so c keeps the old values. Sharing affects freeing as well: after Clear(b) every node of a is gone, and a is set to NIL instead of being cleared a second time.

$ gm2 -fiso sharing.mod IntLists.o -o sharing
$ ./sharing
a: [ 100   2   3 ]
b: [   0 100   2   3 ]
c: [   1   2   3 ]

Lists and arrays

A list grows and shrinks one node at a time, and inserting or removing a node changes only a couple of pointers once its position is known. An array has a fixed size, but reaching its i-th element takes one step, while a list has to be walked from the front. Every node also costs the memory of a pointer and a separate heap allocation. Lists suit data whose size is unknown and which change in the middle; arrays suit data that are indexed, sorted and searched with binary search.

Source

The GNU Modula-2 manual

Niklaus Wirth: Algorithms and Data Structures

In this article we have built linked lists from POINTER TO RECORD nodes, added values at the front, at the end and in sorted order, freed the nodes with DISPOSE, moved the list into a module, removed and reversed nodes, written recursive list procedures and compared shared nodes with copies. The stacks, queues and trees article builds abstract data types from nodes, and the pointers article covers NEW, DISPOSE and NIL.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.