unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

type
  PMyRec = ^MyRec;  {把 PMyRec 定义为下面 MyRec 结构的指针类型}
  MyRec = record
    Name: string[8];
    Age : Word;
    Link: PMyRec;   {结构中同时包含同类型的指针, 用于链接其他同类结构}
  end;

var
  R1,R2,R3,R4: MyRec;

{把 R1、R2、R3、R4 够建成一个环环相扣的"链", 这就是一个简单的"链表"}
procedure TForm1.FormCreate(Sender: TObject);
begin
  R4.Name := '李四';
  R4.Age  := 16;
  R4.Link := nil;

  R3.Name := '张三';
  R3.Age  := 61;
  R3.Link := @R4;

  R2.Name := '钱二';
  R2.Age  := 24;
  R2.Link := @R3;

  R1.Name := '赵一';
  R1.Age  := 42;
  R1.Link := @R2;
end;

{现在 , 通过 R1 即可以访问整个链; 但这个链是单向的, 所以叫"单向链表"}    
procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(R1.Name); {赵一}
  ShowMessage(R1.Link^.Name); {钱二}
  ShowMessage(R1.Link^.Link^.Name); {张三}
  ShowMessage(R1.Link^.Link^.Link^.Name); {李四}
end;

{通过结构指针读取数据可以省略 ^; 所以 Button1Click 可以简写为:}
procedure TForm1.Button2Click(Sender: TObject);
begin
  ShowMessage(R1.Name); {赵一}
  ShowMessage(R1.Link.Name); {钱二}
  ShowMessage(R1.Link.Link.Name); {张三}
  ShowMessage(R1.Link.Link.Link.Name); {李四}
end;

end.
 
 
 
 
 
posted on 2008-03-18 14:23  万一  阅读(3441)  评论(3)  编辑  收藏