《Delphi 算法与数据结构》学习与感悟[8]: 单向链表的添加、删除与遍历

本例效果图:

《Delphi 算法与数据结构》学习与感悟[8]: 单向链表的添加、删除与遍历

unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls;



type

  TForm1 = class(TForm)

    Memo1: TMemo;

    Button1: TButton;

    Button2: TButton;

    Button3: TButton;

    Button4: TButton;

    procedure Button1Click(Sender: TObject);

    procedure Button2Click(Sender: TObject);

    procedure Button3Click(Sender: TObject);

    procedure Button4Click(Sender: TObject);

    procedure FormCreate(Sender: TObject);

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



type

  PMyRec = ^MyRec;

  MyRec = record

    Name: string[8];

    Age : Word;

    Link: PMyRec;

  end;



var

  CurrentNode, FirstNode: PMyRec;



{建立链表}

procedure TForm1.FormCreate(Sender: TObject);

begin

  New(FirstNode);

  FirstNode.Name := '李四';

  FirstNode.Age  := 44;

  FirstNode.Link := nil;

  CurrentNode := FirstNode;



  New(FirstNode);

  FirstNode.Name := '张三';

  FirstNode.Age  := 33;

  FirstNode.Link := CurrentNode;

  CurrentNode := FirstNode;



  New(FirstNode);

  FirstNode.Name := '钱二';

  FirstNode.Age  := 22;

  FirstNode.Link := CurrentNode;

  CurrentNode := FirstNode;



  New(FirstNode);

  FirstNode.Name := '赵一';

  FirstNode.Age  := 11;

  FirstNode.Link := CurrentNode;

  CurrentNode := FirstNode;



  Button1.Caption := '遍历链表';

  Button2.Caption := '插入节点';

  Button3.Caption := '删除节点';

  Button4.Caption := '删除链表';



  Memo1.Align := alLeft;

  Memo1.ScrollBars := ssVertical;

end;



{遍历链表节点}

procedure TForm1.Button1Click(Sender: TObject);

begin

  Memo1.Clear;

  CurrentNode := FirstNode;

  while Assigned(CurrentNode) do

  begin

    Memo1.Lines.Add(CurrentNode.Name + #9 + IntToStr(CurrentNode.Age));

    CurrentNode := CurrentNode.Link;

  end;

end;



{插入节点}

procedure TForm1.Button2Click(Sender: TObject);

var

  NewNode: PMyRec;

begin

  {譬如是插入在第二个节点后面}

  CurrentNode := FirstNode.Link;

  New(NewNode);

  NewNode.Name := 'AAA';

  NewNode.Age  := 100;



  {前后连起来}

  NewNode.Link := CurrentNode.Link;

  CurrentNode.Link := NewNode;



  {调用遍历}

  Button1.Click;

end;



{删除节点}

procedure TForm1.Button3Click(Sender: TObject);

begin

  {譬如是删除第二个节点}

  CurrentNode := FirstNode.Link;        {让 CurrentNode 指向第二个节点}

  if Assigned(CurrentNode.Link) then    {如果 CurrentNode 还有下一个}

  begin

    FirstNode.Link := CurrentNode.Link; {不能断了链}

    Dispose(CurrentNode);               {释放用 New 申请的内存}

  end;



  Button1.Click;

end;



{销毁链表, 释放所有节点}

procedure TForm1.Button4Click(Sender: TObject);

begin

  CurrentNode := FirstNode;     {从链头向下删除}

  while Assigned(FirstNode) do

  begin

    CurrentNode := FirstNode;

    FirstNode := CurrentNode.Link;

    Dispose(CurrentNode);

  end;



  Button1.Click;

end;



end.


 
   

你可能感兴趣的:(Delphi)