我有个双连表例子
Here's the code for a simple generic unordered linked-list class. OK, so there's not much you can do with it as it stands but it is easily extended to real working code. My Maps library consists of five generic associative containers based on a doubly-linked list, a hashed array tree, a hash table, a binary search tree, and a treap. They offer a range of performance tradeoffs depending upon whether you project needs addition or searching or deletion, etc., to be fastest. The simple code below, though, should give you the idea. Even this list is truly generic. A very simple test program is available to exercise the list. Click here to download the sample code.
type
PNode = ^TNode
TNode = record
Item : TVarRec
Left : PNode
Right : PNode
end
type
TGenericList = class
private
Head : PNode
Tail : PNode
SP: Pnode
protected
public
constructor Create
destructor Destroy
override
function AddItem(const Item : TVarRec) : PNode
procedure AddItems(Items : array of const)
procedure Clear
function First : PNode
function GetItem(const Index : PNode) : TVarRec
function Last : PNode
function Next : PNode
function Prev : PNode
end
{ TGenericList }
function TGenericList.AddItem(const Item : TVarRec) : PNode
var
P : PNode
begin
GetMem(P, SizeOf(Tnode))
CopyVarRec(Item, P.Item)
P.Left := nil
P.Right := Head
if (Tail = nil) then
begin
{ previously empty }
Tail := P
Head := Tail
end
else
begin
Head.Left := P
Head := P
end
Result := P
end
procedure TGenericList.AddItems(Items: array of const)
var
n: integer
begin
for n:= 0 to High(Items) do
AddItem(Items[n])
end
procedure TGenericList.Clear
var
P : PNode
begin
while Head <> nil do
begin
P := Head
Head := Head.Right
ClearVarRec(P.Item)
FreeMem(P)
end
Tail := nil
end
constructor TGenericList.Create
begin
inherited Create
Head := nil
Tail := nil
end
destructor TGenericList.Destroy
begin
Clear
inherited Destroy
end
function TGenericList.First : PNode
begin
SP := Head
Result := SP
end
function TGenericList.GetItem(const Index : PNode) : TVarRec
begin
Result := Index.Item
end
function TGenericList.Last : PNode
begin
SP := Tail
Result := SP
end
function TGenericList.Next : PNode
begin
if SP <> nil then
begin
SP := SP.Right
end
Result := SP
end
function TGenericList.Prev : PNode
begin
if SP <> nil then
begin
SP := SP.Left
end
Result := SP
end;