ZetCode

Linked lists in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

A linked list is a sequence of nodes, where each node stores a value and a pointer to the next node. The list has no fixed length and no contiguous block of memory: nodes are allocated one at a time, and the links define the order. This article builds a singly linked list from two nodes linked by hand, then adds traversal, append, and freeing, moves the helpers into a unit, adds insertion, deletion, and reversal, and finishes with a doubly linked list.

Two nodes linked by hand

A node is a record with a value and a Next pointer. The pointer type must be declared before the record, because the record refers to itself. New allocates one node on the heap and Dispose releases it. The caret ^ dereferences a pointer, so A^.Value is the field of the node that A points to.

hand.pas
program hand;
{$mode objfpc}{$H+}

type
  PNode = ^TNode;
  TNode = record
    Value: Integer;
    Next: PNode;
  end;

var
  A, B: PNode;

begin
  New(A);
  A^.Value := 10;
  New(B);
  B^.Value := 20;
  A^.Next := B;
  B^.Next := nil;
  WriteLn(A^.Value);
  WriteLn(A^.Next^.Value);
  Dispose(B);
  Dispose(A);
end.

A^.Next := B stores the address of the second node in the first one, so A^.Next^.Value is 20. B^.Next := nil marks the end of the chain. The two nodes are independent allocations, and they are disposed in the reverse order of creation only for symmetry; either order works as long as no pointer is followed after its target is freed.

$ fpc -gl hand.pas
$ ./hand
10
20

Walking the chain

A list is referenced by its first node, called the head. To visit every node, copy the head into a walking pointer and follow Next until the pointer becomes nil. The head itself stays unchanged, so the list can be traversed again from the beginning.

walk.pas
program walk;
{$mode objfpc}{$H+}

type
  PNode = ^TNode;
  TNode = record
    Value: Integer;
    Next: PNode;
  end;

var
  First, Second, Third, Current: PNode;

begin
  New(First);
  First^.Value := 10;
  New(Second);
  Second^.Value := 20;
  New(Third);
  Third^.Value := 30;
  First^.Next := Second;
  Second^.Next := Third;
  Third^.Next := nil;

  Current := First;
  while Current <> nil do
  begin
    WriteLn(Current^.Value);
    Current := Current^.Next;
  end;

  Dispose(Third);
  Dispose(Second);
  Dispose(First);
end.

The loop prints 10, 20, and 30 and stops when Current reaches the nil stored in the last node. The walking pointer is a local variable; the list's head is still First. A traversal is linear in the number of nodes, because each step follows exactly one link.

$ fpc -gl walk.pas
$ ./walk
10
20
30

Appending with a procedure

The hand-built list does not scale: every new node would need its own variable and its own link assignment. A helper function allocates a node with the given value, and an Append procedure walks to the last node and links the new one after it. The head is passed as a var parameter so the procedure can set it when the list is empty.

listappend.pas
program listappend;
{$mode objfpc}{$H+}

type
  PNode = ^TNode;
  TNode = record
    Value: Integer;
    Next: PNode;
  end;

function NewNode(Value: Integer): PNode;
begin
  New(Result);
  Result^.Value := Value;
  Result^.Next := nil;
end;

procedure Append(var Head: PNode; Value: Integer);
var
  Current: PNode;
begin
  if Head = nil then
    Head := NewNode(Value)
  else
  begin
    Current := Head;
    while Current^.Next <> nil do
      Current := Current^.Next;
    Current^.Next := NewNode(Value);
  end;
end;

procedure PrintList(Head: PNode);
var
  Current: PNode;
begin
  Current := Head;
  while Current <> nil do
  begin
    Write(Current^.Value);
    if Current^.Next <> nil then
      Write(' ');
    Current := Current^.Next;
  end;
  WriteLn;
end;

var
  Head: PNode;

begin
  Head := nil;
  Append(Head, 10);
  Append(Head, 20);
  Append(Head, 30);
  PrintList(Head);
end.

NewNode returns a pointer to a node whose Next is already nil. Append handles the empty list by assigning the new node to Head; otherwise it walks to the last node and attaches the new one. Appending is linear in the current length, because the procedure has no tail pointer to jump to the end. The process exit reclaims the three nodes, but the next section adds the release procedure so a long-running program does not leak.

$ fpc -gl listappend.pas
$ ./listappend
10 20 30

Freeing the list

Releasing a list must save the next pointer before disposing the current node. After Dispose(Head), the memory is invalid and its Next field must not be read. FreeList therefore copies Head^.Next into a local variable, disposes the node, and moves the head forward. At the end the head is nil.

listfree.pas
program listfree;
{$mode objfpc}{$H+}

type
  PNode = ^TNode;
  TNode = record
    Value: Integer;
    Next: PNode;
  end;

function NewNode(Value: Integer): PNode;
begin
  New(Result);
  Result^.Value := Value;
  Result^.Next := nil;
end;

procedure Append(var Head: PNode; Value: Integer);
var
  Current: PNode;
begin
  if Head = nil then
    Head := NewNode(Value)
  else
  begin
    Current := Head;
    while Current^.Next <> nil do
      Current := Current^.Next;
    Current^.Next := NewNode(Value);
  end;
end;

procedure PrintList(Head: PNode);
var
  Current: PNode;
begin
  Current := Head;
  while Current <> nil do
  begin
    Write(Current^.Value);
    if Current^.Next <> nil then
      Write(' ');
    Current := Current^.Next;
  end;
  WriteLn;
end;

procedure FreeList(var Head: PNode);
var
  Next: PNode;
begin
  while Head <> nil do
  begin
    Next := Head^.Next;
    Dispose(Head);
    Head := Next;
  end;
end;

var
  Head: PNode;

begin
  Head := nil;
  Append(Head, 10);
  Append(Head, 20);
  Append(Head, 30);
  PrintList(Head);
  FreeList(Head);
  WriteLn('empty: ', Head = nil);
end.

The var parameter lets FreeList update the caller's head, so the list cannot be used accidentally after it has been released. The loop runs once per node and uses constant extra space. If the program exits without calling FreeList, the operating system reclaims the memory, but a long-running program would leak one node per list.

$ fpc -gl listfree.pas
$ ./listfree
10 20 30
empty: TRUE

Moving the helpers into a unit

The last program already has four helpers, and every later operation needs them again. Instead of copying them into each program, they move into a unit. The node types and the procedure headers go into the interface section, so a program that uses the unit can declare PNode variables and call the helpers. The bodies go into the implementation section unchanged.

intlist.pas
unit intlist;
{$mode objfpc}{$H+}

interface

type
  PNode = ^TNode;
  TNode = record
    Value: Integer;
    Next: PNode;
  end;

function NewNode(Value: Integer): PNode;
procedure Append(var Head: PNode; Value: Integer);
procedure PrintList(Head: PNode);
procedure FreeList(var Head: PNode);

implementation

function NewNode(Value: Integer): PNode;
begin
  New(Result);
  Result^.Value := Value;
  Result^.Next := nil;
end;

procedure Append(var Head: PNode; Value: Integer);
var
  Current: PNode;
begin
  if Head = nil then
    Head := NewNode(Value)
  else
  begin
    Current := Head;
    while Current^.Next <> nil do
      Current := Current^.Next;
    Current^.Next := NewNode(Value);
  end;
end;

procedure PrintList(Head: PNode);
var
  Current: PNode;
begin
  Current := Head;
  while Current <> nil do
  begin
    Write(Current^.Value);
    if Current^.Next <> nil then
      Write(' ');
    Current := Current^.Next;
  end;
  WriteLn;
end;

procedure FreeList(var Head: PNode);
var
  Next: PNode;
begin
  while Head <> nil do
  begin
    Next := Head^.Next;
    Dispose(Head);
    Head := Next;
  end;
end;

end.

The unit contains no new code; it is the program from the previous section without its main block. The remaining examples in the singly linked part start with uses intlist; and show only the operation that is new. The compiler finds intlist.pas in the current directory and compiles it together with the program that uses it.

Inserting at the front and in the middle

Inserting at the front is constant time: allocate a node, point it at the old head, and update the head. Inserting after an existing node is also constant time, because the node is already known. Both operations only rearrange pointers; no existing value is moved. NewNode, PrintList, and FreeList come from the intlist unit.

listinsert.pas
program listinsert;
{$mode objfpc}{$H+}

uses intlist;

procedure Prepend(var Head: PNode; Value: Integer);
var
  Node: PNode;
begin
  Node := NewNode(Value);
  Node^.Next := Head;
  Head := Node;
end;

procedure InsertAfter(Node: PNode; Value: Integer);
var
  NewOne: PNode;
begin
  if Node = nil then
    Exit;
  NewOne := NewNode(Value);
  NewOne^.Next := Node^.Next;
  Node^.Next := NewOne;
end;

var
  Head: PNode;

begin
  Head := nil;
  Prepend(Head, 30);
  Prepend(Head, 20);
  Prepend(Head, 10);
  Write('prepend:         ');
  PrintList(Head);
  InsertAfter(Head^.Next, 25);
  Write('insert after 20: ');
  PrintList(Head);
  FreeList(Head);
end.

Three prepends produce the order 10, 20, 30, the reverse of the insertion order. InsertAfter(Head^.Next, 25) inserts 25 after the node that holds 20, so the list becomes 10, 20, 25, 30. A singly linked list cannot walk backward, which is why insertion before a node requires a reference to the previous node.

$ fpc -gl listinsert.pas
$ ./listinsert
prepend:         10 20 30
insert after 20: 10 20 25 30

Deleting a node

Deleting a node requires its predecessor, because the predecessor's Next pointer must skip over the removed node. The search keeps two pointers, Previous and Current, and handles the head as a special case: when the value is in the first node, there is no predecessor, so the head itself moves forward.

listdelete.pas
program listdelete;
{$mode objfpc}{$H+}

uses intlist;

procedure DeleteValue(var Head: PNode; Value: Integer);
var
  Current, Previous: PNode;
begin
  Current := Head;
  Previous := nil;
  while Current <> nil do
  begin
    if Current^.Value = Value then
    begin
      if Previous = nil then
        Head := Current^.Next
      else
        Previous^.Next := Current^.Next;
      Dispose(Current);
      Exit;
    end;
    Previous := Current;
    Current := Current^.Next;
  end;
end;

var
  Head: PNode;
  I: Integer;

begin
  Head := nil;
  for I := 1 to 5 do
    Append(Head, I * 10);
  Write('before:      ');
  PrintList(Head);
  DeleteValue(Head, 30);
  Write('delete 30:   ');
  PrintList(Head);
  DeleteValue(Head, 10);
  Write('delete head: ');
  PrintList(Head);
  DeleteValue(Head, 99);
  Write('delete 99:   ');
  PrintList(Head);
  FreeList(Head);
end.

The first deletion removes the node that holds 30, which is in the middle. The second removes the head, so Head moves to the next node. The third searches for 99, finds nothing, and leaves the list unchanged. The procedure removes only the first match; a list that may contain duplicates needs a loop that continues after a deletion.

$ fpc -gl listdelete.pas
$ ./listdelete
before:      10 20 30 40 50
delete 30:   10 20 40 50
delete head: 20 40 50
delete 99:   20 40 50

Reversing a list

Reversal walks the list once and flips each Next pointer. Three pointers are enough: Previous is the part already reversed, Current is the node being processed, and Next saves the rest of the list before the link is changed. At the end, the old tail is the new head.

listreverse.pas
program listreverse;
{$mode objfpc}{$H+}

uses intlist;

procedure Reverse(var Head: PNode);
var
  Previous, Current, Next: PNode;
begin
  Previous := nil;
  Current := Head;
  while Current <> nil do
  begin
    Next := Current^.Next;
    Current^.Next := Previous;
    Previous := Current;
    Current := Next;
  end;
  Head := Previous;
end;

var
  Head: PNode;
  I: Integer;

begin
  Head := nil;
  for I := 1 to 5 do
    Append(Head, I * 10);
  Write('before: ');
  PrintList(Head);
  Reverse(Head);
  Write('after:  ');
  PrintList(Head);
  FreeList(Head);
end.

The loop changes one link per iteration and never allocates memory, so reversal is linear in the number of nodes and uses constant extra space. The order of the assignments matters: Next must be saved before Current^.Next is overwritten, or the rest of the list is lost.

$ fpc -gl listreverse.pas
$ ./listreverse
before: 10 20 30 40 50
after:  50 40 30 20 10

A doubly linked list

A doubly linked list adds a Prev pointer to each node. The list keeps both a head and a tail, so appending is constant time and the list can be traversed in either direction. The price is one extra pointer per node and two links to update on every insertion or deletion.

doubly.pas
program doubly;
{$mode objfpc}{$H+}

type
  PNode = ^TNode;
  TNode = record
    Value: Integer;
    Prev, Next: PNode;
  end;

procedure Append(var Head, Tail: PNode; Value: Integer);
var
  Node: PNode;
begin
  New(Node);
  Node^.Value := Value;
  Node^.Next := nil;
  Node^.Prev := Tail;
  if Tail = nil then
    Head := Node
  else
    Tail^.Next := Node;
  Tail := Node;
end;

var
  Head, Tail, Current: PNode;
  I: Integer;

begin
  Head := nil;
  Tail := nil;
  for I := 1 to 5 do
    Append(Head, Tail, I * 10);

  Write('forward:  ');
  Current := Head;
  while Current <> nil do
  begin
    Write(Current^.Value, ' ');
    Current := Current^.Next;
  end;
  WriteLn;

  Write('backward: ');
  Current := Tail;
  while Current <> nil do
  begin
    Write(Current^.Value, ' ');
    Current := Current^.Prev;
  end;
  WriteLn;

  while Head <> nil do
  begin
    Current := Head^.Next;
    Dispose(Head);
    Head := Current;
  end;
end.

Append allocates the node itself, links it after the tail, and moves the tail in constant time; no walk to the end is needed. The main block walks the list twice: forward from the head through Next, and backward from the tail through Prev. The final loop releases the nodes through the Next chain only. The program does not use the intlist unit, because its node type has the extra Prev field.

$ fpc -gl doubly.pas
$ ./doubly
forward:  10 20 30 40 50
backward: 50 40 30 20 10

Arrays or lists?

An array stores elements contiguously and gives constant-time access by index. A linked list gives constant-time insertion and deletion at a known position, but reaching position n costs n steps. Appending to the singly linked list above is linear; keeping a tail pointer, as in the doubly linked version, makes it constant time. Searching is linear in both structures.

Linked lists are the right choice when the program inserts and removes elements while it runs and does not need random access. They are also the building block for stacks, queues, and trees. When the data is mostly read and indexed, a dynamic array is simpler and faster because its elements are next to each other in memory, which the CPU cache prefers.

Next steps

The stacks and queues article uses the ends of a list for LIFO and FIFO access, and the binary trees article gives each node two child pointers instead of one. The pointers article explains the allocation and disposal that every node relies on.

Source

Free Pascal Reference guide

Free Pascal: pointers

Linked list on Wikipedia

In this article we linked two nodes by hand, walked a chain, appended nodes with a procedure, freed the list safely, moved the helpers into a unit, prepended and inserted in the middle, deleted a node and the head, reversed a singly linked list, and built a doubly linked list with forward and backward traversal. The series continues with stacks and queues in Pascal.

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 Pascal tutorials.