TQueue 和 TStack, 一个是队列列表, 一个是堆栈列表; 一个是先进先出, 一个是先进后出.
TQueue 主要有三个方法、一个属性:
Enqueue(入列)、Dequeue(出列)、Peek(查看下一个要出列的元素);
Count(元素总数).
-------------------------------------------------------------------------------------------------------------------------------------------------------------
1 unit Unit1; 2 3 interface 4 5 uses 6 Generics.Collections, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, 7 System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; 8 9 type 10 TRec = record 11 Name: string; 12 Age: Word; 13 end; 14 15 type 16 TForm1 = class(TForm) 17 Memo1: TMemo; 18 Button1: TButton; 19 Button2: TButton; 20 Button3: TButton; 21 procedure FormCreate(Sender: TObject); 22 procedure FormDestroy(Sender: TObject); 23 procedure Button1Click(Sender: TObject); 24 procedure Button2Click(Sender: TObject); 25 procedure Button3Click(Sender: TObject); 26 private 27 var 28 Queue: TQueue<TRec>; {定义一个泛型 TQueue 类, 这指定了要用于上面定义的 TRec 记录} 29 public 30 { Public declarations } 31 end; 32 33 var 34 Form1: TForm1; 35 36 implementation 37 38 {$R *.dfm} 39 40 {入列: Enqueue} 41 42 procedure TForm1.Button1Click(Sender: TObject); 43 var 44 rec: TRec; 45 begin 46 rec.Name := StringOfChar(Char(65 + Random(26)), 3); 47 rec.Age := Random(150); 48 Queue.Enqueue(rec); 49 Text := Format(‘当前队列成员总数: %d‘, [Queue.Count]); 50 51 {让 Memo1 配合显示} 52 Memo1.Lines.Add(Format(‘%s, %d‘, [rec.Name, rec.Age])); 53 54 end; 55 56 {出列: Dequeue} 57 procedure TForm1.Button2Click(Sender: TObject); 58 var 59 rec: TRec; 60 begin 61 if Queue.Count = 0 then 62 Exit; 63 rec := Queue.Dequeue; 64 ShowMessage(Format(‘%s, %d‘, [rec.Name, rec.Age])); 65 Text := Format(‘当前队列成员总数: %d‘, [Queue.Count]); 66 67 {让 Memo1 配合显示} 68 Memo1.Lines.Delete(0); 69 end; 70 71 {下一个出列的元素: Peek} 72 procedure TForm1.Button3Click(Sender: TObject); 73 var 74 rec: TRec; 75 begin 76 if Queue.Count = 0 then 77 Exit; 78 rec := Queue.Peek; 79 ShowMessage(Format(‘%s, %d‘, [rec.Name, rec.Age])); 80 end; 81 82 procedure TForm1.FormCreate(Sender: TObject); 83 begin 84 Queue := TQueue<TRec>.Create; 85 86 Memo1.Clear; 87 Button1.Caption := Button1.Caption + ‘ 入列‘; 88 Button2.Caption := Button2.Caption + ‘ 出列‘; 89 Button3.Caption := Button3.Caption + ‘ 下一个出列的...‘; 90 end; 91 92 procedure TForm1.FormDestroy(Sender: TObject); 93 begin 94 Queue.Free; 95 end; 96 97 end.