我正在尝试在 Delphi 中创建一个链表实现,但无法创建节点,因为我需要检查头指针是否为空。我现在使用的代码如下所示:
procedure LinkedList.addNode(newNode: Node);
var lastNode: Node;
begin
if pHead = nil then
pHead := @newNode
else
lastNode := peekLastNode(pHead^);
lastNode.pNext := @newNode;
end;
Run Code Online (Sandbox Code Playgroud)
程序在添加一个元素后就冻结了,所以 nil 部分是无限期的问题。
这是整个程序:
program LinkedListImplementation;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
Node = record
data: string;
pNext: ^Node;
end;
type
LinkedList = class
pHead: ^Node;
function peekLastNode (currentNode: Node) : Node;
function listToString(currentNode: Node) : String;
procedure addNode (newNode: Node);
end;
//the initial parameter for this function is LinkedList.pHead^
function LinkedList.peekLastNode (currentNode: …Run Code Online (Sandbox Code Playgroud)