单向链表的添加、删除与遍历

减小字体 增大字体 作者:万一  来源:万一的博客  发布时间:2010-11-13 13:16:20

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.
效果图:

Tags:

作者:万一
  • 好的评价 如果您觉得此文章好,就请您
      0%(0)
  • 差的评价 如果您觉得此文章差,就请您
      0%(0)

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论