| Код | type TPNode= ^TNode; TNode= record name, surname: string; // Имя, фамилия next: TPNode; // Указатель на следующий узел end; TQueue= record // Непосредственно сама очередь head, tail: TPNode; // Указатель на голову и хвост end;
{-----------------------------------------------} // Добавление в конец (хвост) очереди procedure Push(var theQueue: TQueue; theName, theSurname: string); var node: TPNode; begin new(node); // Новый узел node^.name:= theName; // Задаём имя новому узлу node^.surname:= theSurname; // Задаём фамилию node^.next:= nil; // Т.к. этот узел теперь будет последним, то значит // он не на что не ссылается. if (theQueue.tail = nil) then // Вариант когда в очереди нет ни одного элемента begin theQueue.head:= node; // Соответственно и голова и хвост будут указывать theQueue.tail:= node; // на вновь созданный узел end else begin theQueue.tail^.next:= node;// Иначе просто добавляем в хвост очереди theQueue.tail:= node; end; end; {-----------------------------------------------} // Извлекаем с начала очереди, если извлечение прошло удачно, то // возвращаем true, иначе false function Pop(var theQueue: TQueue; var theName, theSurname: string): boolean; var node: TPNode; begin if (theQueue.head = nil) then // Если очередь пуста, то выходим begin Pop:= false; exit; end; node:= theQueue.head; // Переприсваеваем указатель на удаляемый элемент theQueue.head:= node^.next; // Указатель на голову в списке спускаем ниже if (theQueue.head = nil) then // Если удаляемый элемент был последний в очереди theQueue.tail:= nil; theName:= node^.name; theSurname:= node^.surname; dispose(node); // Удаляем узел Pop:= true; end; {-----------------------------------------------} procedure Print(theQueue: TQueue); begin while (theQueue.head <> nil) do begin writeln(theQueue.head^.name, ' ', theQueue.head^.surname); theQueue.head:= theQueue.head^.next; end; end; {-----------------------------------------------}
var name, surname: string; queue: TQueue;
begin queue.head:= nil; queue.tail:= nil; writeln('Test: Push -> Pop'); Push(queue, 'A_name', 'A_surname'); Push(queue, 'B_name', 'B_surname'); Push(queue, 'C_name', 'C_surname'); while (Pop(queue, name, surname)) do writeln(name, ' ', surname); writeln; writeln('Test: Push -> Print'); Push(queue, 'D_name', 'D_surname'); Push(queue, 'E_name', 'E_surname'); Push(queue, 'F_name', 'F_surname'); Print(queue); end.
|
|