A linked list is a data structure consisting of elements, each of which is represented as a node composed of two parts:
Example: declare a linked list of integers.
type
node_ptr = ^node;
node = record
data : integer;
next : node_ptr;
end;
Example: we assume the linked list is declared as in the example above.
var
head, current : node_ptr;
{ . . . }
{create list}
new(head);
{initialize data field 1st node}
head^.data := 12;
{initialise next field 1st node}
new(head^.next);
current := head^.next;
Example: the following program creates and initializes a linked list of seven integers.
program example;
type
node_ptr = ^node;
node = record
data : integer;
next : node_ptr;
end;
var
head, current : node_ptr;
k : integer;
begin
new(head);
randomize;
{first node}
head^.data := random(100);
write(head^.data, ' ');
new(head^.next);
current := head^.next;
{more nodes}
for k := 1 to 5 do
begin
current^.data := random(100);
write(current^.data, ' ');
new(current^.next);
current := current^.next;
end;
{last node}
current^.data := random(100);
writeln(current^.data);
current^.next := nil; {last node}
writeln('linked list created');
writeln('display list');
current := head;
while current <> nil do
begin
write(current^.data, ' ');
current := current^.next;
end;
end.