从链接列表中获取项目

时间:2015-12-17 10:17:51

标签: delphi linked-list pascal

我有这个:

declare @MyTable table(pkid int, title varchar(100), name varchar(100));
insert into @MyTable(pkid, title, name) values
    (1, 'User 2', 'Some value for "User 2"')
    , (2, 'User', 'Some value for the user')
    , (3, 'User', 'Some value for the user')
    , (4, 'Admin', 'Some value for the Admin')
    , (5, 'Guest 1', 'Some value for "Guest 1"')
    , (6, 'Guest', 'Some value for the guest')
    ;

有没有办法在第二个索引上获取项目?

type PList = ^TSome; TSome = record next :PList; ... var tmp:PList; ... begin tmp := list; while tmp^.next <> nil do tmp := tmp^.next; end 类似,但由于这不是数组,因此无法实现。

2 个答案:

答案 0 :(得分:2)

这就是通常的做法:

var
  tmp: PList;
  index: Integer;
begin
  index := 0;
  tmp := list;

  repeat
    tmp := tmp^.next;
    Inc(Index);
  until (tmp = nil) or (index = 2);
end;

答案 1 :(得分:1)

但这会是懒散的!比阵列慢得多。

TSome = record
     next :PList;
     ...

     function GetNext(skip: cardinal): TSome;
     property ArrayLike[index: cardinal]: TSome read GetNext; default;
end;

....

{$T+}
function TSome.GetNext(skip: cardinal): TSome;
type PSome = PList;
var candidate: PSome;
begin
  candidate := @Self;
  while skip > 0 do
    candidate := candidate.Next;
    if candidate = nil then raise EBoundsError.Create('out of index');
    Dec(skip);
  end;
  Result := candidate^;
end;

...

var x: TSome;

 x[0] = x.ArrayLike[0] = x;

警告:既然你使用的是记录而不是类 - 你得到的是记录的复制而不是记录本身;

var x,y: TSome; y := x;类似 - 您执行新数据复制,而不是指向相同数据的第二个指针。

这个以及列表结构的问题会使这种访问速度变慢,比数组慢得多。

并且

var x,y,z: TSome; i: integer;

x.SomeValue := 1;
y.SomeValue := 2;
x.Next := @y;

i := x[1].SomeValue; 
// i == 2 ( making copy of y, then taking a SomeValue from it)

x[1].SomeValue := 10; 
z := x[1];
z.SomeValue := 20;

i := x[1].SomeValue; 
// still i == 2 - we were NOT changing the value in y itself, we were making DATA COPIES of y and changing COPIES