
(* This program reads in names of up to 20 characters and builds
an alphabetical list. 

variables - 
   Head - pointer to mark the head of the list
   Name - character array to hold a name in the list
   ResponseChar - used to ask user for more input   *)

program SortList(Input,Output); 

const NameLength = 20;

type  ListElement = packed array[1..NameLength] of char;
      ListPtr = ^ListRecord;
      ListRecord = record
                Person : ListElement;
                Next : ListPtr
                end; (*record*)

var   Head : ListPtr;
      Name : ListElement;
      ResponseChar : char;
      NameBuffer : array[1..NameLength] of char;
      TempPtr : ListPtr;

(*----------------------------------------------*)
procedure InsertName(Name : ListElement); (* Procedure to enter names to the
           list.  It add names to the front of the list unless they are
           alphabetically greater.  It scans the list, setting SwitchOrder
           when the correct location is found and adding the name in that
           location. 

Variables - 
           Pointer - primary pointer used in setting up linked list
           SwitchPointer - temporary pointer used when switching list order
           NewPointer- pointer to point to new name being inserted
           SwitchOrder - boolean flag to indicate order needs switching  *)

var Pointer,SwitchPointer,NewPointer : ListPtr;
    SwitchOrder : boolean;

begin
    SwitchOrder := true;
    Pointer := Head; 
    while (SwitchOrder) and (Pointer <> nil) do 
        if Name < Pointer^.Person then SwitchOrder := false 
        else begin 
            SwitchPointer := Pointer;
            Pointer := Pointer^.Next 
            end; (* else *)
    new(NewPointer); 
    NewPointer^.Person := Name;
    NewPointer^.Next := Pointer;
    if Pointer = Head then Head := NewPointer 
    else SwitchPointer^.Next := NewPointer 
end;(* InsertName *)

(*----------------------------------------------*)

procedure ReadName(var Name : ListElement); (* input a name *)
var i : integer;

begin
    for i := 1 to NameLength do NameBuffer[i] := ' ';
    for i := 1 to NameLength do
         if not eoln then read(NameBuffer[i]);
    pack(NameBuffer,1,Name);
    readln
end;(* ReadName *)

(*-----------------------------------------------*)
procedure WriteName; (* output a linked list *)

begin
    TempPtr := Head;
    while TempPtr <> nil do begin
        writeln(TempPtr^.Person); 
        TempPtr := TempPtr^.Next
        end (* whlie *)
end;(* WriteName *)

(*--------------------------------------------------*)
begin (* SortList *)
    Head := nil;  
    writeln('Begin inputting names ');
    repeat
        ReadName(Name);  
        InsertName(Name);
        write('More names? ');
        readln(ResponseChar);
    until (ResponseChar in ['n','N']);
    WriteName 
end.(* SortList *)

