{ topsort.txt -- Algorithm #1: Topological Sort by Tom Swan }

{ Initialize }
New(head);
tail <- head;

{ Input data }
Read(pitem);
while not Eof(input) do
begin
  Read(item);
  a <- Search(pitem);
  b <- Search(item);
  Create new follower record f;
  Identify f as item at b
  Link f into chain at a
  Read(pitem);
end;

{ Find leaders }
a <- head;
head <- nil;
while a <> tail do
begin { Search list }
  b <- a; a <- a^.next;
  if b has no predecessors then
  begin { Link b into list at head }
    b^.next <- head;
    head <- b;
  end;
end;

{ Sort and output }
b <- head;
while b <> nil do
begin { Search list }
  c <- b^.chain;
  b <- b^.next;
  while c <> nil do
  begin { Output item }
    Write(b);
    a <- c^.id;
    if a has no predecessors then
    begin { Link a into leader list at b }
      a^.next <- b;
      b <- a;
    end;
    c <- c^.next;
  end;
end;


(*
// --------------------------------------------------------------
// Copyright (c) 1993 by Tom Swan. All rights reserved
// Revision 1.00    Date: 01/16/1993   Time: 11:36 am
*)
