您的位置:首页 > 编程语言 > Delphi

在Delphi中编写自己的链表管理类。 推荐

2008-10-13 14:00 483 查看
在Delphi中使用链表,我们第一个想到的自然是使用TList类来实现(以前我也是这样做的)。但是当我们仔细看一下TList的实现就会发现这个类的实现其实使用的是数组的方式来实现的。哪如何编写自己的链表管理类呢?
其实这个问题在几乎每个将数据结构的书中都有讲到。这里我大概写一下我在写自己的链表管理中使用的方法。如有不正确的地方希望大家指正。
首先定义一个保存数据的结构:
PMyInfo = ^TMyInfo;
TMyInfo = record
NameID:Integer;
Name:String[20];
Age:Word;
Next: PMyInfo;
End;

定义一个类:
type
TListControl = class
private
FCount: Integer;
{ Private declarations }
protected
public
constructor Create;
destructor Destroy; override;
//向链表中加入信息
procedure AddList(NameID:Integer;Name:String;Age:Integer);
//根据条件删除信息
procedure DelList(NameID:Integer);
//根据条件查询信息
procedure SelList(NameID:Integer;var Name:String;var Age:Integer);
//清空链表中的信息
procedure CleatList;
//得到链表数量
property Count:Integer read FCount;
end;

implementation
procedure TListControl.AddList(NameID: Integer; Name: String;
Age: Integer);
var
FMyInfo:PMyInfo;
begin
Entercriticalsection(FCriticalSection);
try
New(FMyInfo);
FMyInfo.NameID:=NameID;
FMyInfo.Name:=Name;
FMyInfo.Age:=Age;
FMyInfo.Next:=nil;
//头指针是否为空
if not Assigned(FFirst) then
begin
FFirst:=FMyInfo;
end
else
begin
FLast.Next:=FMyInfo;
end;
FLast:=FMyInfo;
Inc(FCount);
finally
Leavecriticalsection(FCriticalSection);
end;
end;

procedure TListControl.ClearList;
var
FMyInfo,FOldMyInfo:PMyInfo;
begin
Entercriticalsection(FCriticalSection);
try
FMyInfo:=FFirst;
while Assigned(FMyInfo) do
begin
FOldMyInfo:=FMyInfo.Next;
Dispose(FMyInfo);
FMyInfo:=FOldMyInfo;
end;
FCount:=0;
FLast:=nil;
finally
Leavecriticalsection(FCriticalSection);
end;
end;

constructor TListControl.Create;
begin
InitializeCriticalSection(FCriticalSection);
FCount:=0;
end;

procedure TListControl.DelList(NameID: Integer);
var
FMyInfo,FOldMyInfo:PMyInfo;
begin
Entercriticalsection(FCriticalSection);
try
FMyInfo:=FFirst;
FOldMyInfo:=nil;
while Assigned(FMyInfo) do
begin
if FMyInfo.NameID = NameID then
begin
//删除的是否是尾指针
if FMyInfo = FLast then
begin
FLast:=FOldMyInfo;
end
else
begin
FOldMyInfo.Next:=FMyInfo.Next;
end;
Dispose(FMyInfo);
Dec(FCount);
break;
end;
FOldMyInfo:=FMyInfo;
FMyInfo:=FMyInfo.Next;
end;
finally
Leavecriticalsection(FCriticalSection);
end;
end;

destructor TListControl.Destroy;
begin
DeleteCriticalSection(FCriticalSection);
inherited;
end;

procedure TListControl.SelList(NameID: Integer; var Name: String;
var Age: Integer);
var
FMyInfo,FOldMyInfo:PMyInfo;
begin
Entercriticalsection(FCriticalSection);
try
FMyInfo:=FFirst;
FOldMyInfo:=nil;
while Assigned(FMyInfo) do
begin
if FMyInfo.NameID = NameID then
begin
Name:=FMyInfo.Name;
Age:=FMyInfo.Age;
break;
end;
FOldMyInfo:=FMyInfo;
FMyInfo:=FMyInfo.Next;
end;
finally
Leavecriticalsection(FCriticalSection);
end;
end;

以上我大致写了一下自己编写链表类的实现,现在有个问题我一直没有想出来,就是如果对于这个类写Sort(排序)方法,在TList类中有个Sort方法,此方法我看了一下使用的是快速排序法进行排序,至于排序条件它是透出了一个用户自己的函数来实现的。我在我写的类中试着也用这种方法实现,可是没有实现,希望实现过的朋友不吝赐教。谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  职场 Delphi 休闲 链表