DELPHI中的链表问题,删除节点的时候我把上一个指针移到下一个节点头,跳过的那个节点的内存怎么释放谢谢
2个回答
展开全部
先用一个指针标记要释放的那个节点,然后把前后两个节点链接,最后释放指针指向的这个节点。举个例子,假设head是链表头,现在要删除链表中的第i个节点:
type
PNode = ^TNode;
TNode = record
data: Integer;
next: PNode;
end;
procedure DeleteNode(var Head: PNode; Index: Integer);
var
cur, p: PNode;
i: Integer;
begin
if (Head = nil) or (Index < 1) then Exit;
if Index = 1 then
begin
p := Head;
Head := p^.next;
Dispose(p);
Exit;
end;
cur := Head;
i := 1;
while (i < Index - 1) and (cur <> nil) do
begin
cur := cur^.next;
Inc(i);
end;
if cur = nil then Exit;
p := cur^.next;
if p <> nil then
begin
cur^.next := p^.next;
Dispose(p);
end;
end;
type
PNode = ^TNode;
TNode = record
data: Integer;
next: PNode;
end;
procedure DeleteNode(var Head: PNode; Index: Integer);
var
cur, p: PNode;
i: Integer;
begin
if (Head = nil) or (Index < 1) then Exit;
if Index = 1 then
begin
p := Head;
Head := p^.next;
Dispose(p);
Exit;
end;
cur := Head;
i := 1;
while (i < Index - 1) and (cur <> nil) do
begin
cur := cur^.next;
Inc(i);
end;
if cur = nil then Exit;
p := cur^.next;
if p <> nil then
begin
cur^.next := p^.next;
Dispose(p);
end;
end;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询