我在理解 Pascal 中设置为 nil 的指针的行为时遇到了问题。我正在使用涡轮帕斯卡 7.0。 似乎当我将两个指针 head,tail 设置为 nil 时......它们似乎总是指向未来的相同值,即使它们被分配给不同的值。
在下面的代码中,当我注释掉了问题区域,并得到了预期的结果。
当我从这对行中删除注释时 head:=nil; 尾巴:=无;
在取消引用时,“头”指针似乎总是采用赋予“尾”指针的值。提供的任何见解将不胜感激。
program LinkedListTest;
type
ListNodePtr = ^ListNode;
ListNode = record
key,cycleLength: integer;
NodePtr: ListNodePtr;
end;
{
We have just defined the node of a linked list.
Next we declare our head which is the pointer to the first node
and the tail which points to the last node.
The head helps us find our first node in the list
the tail helps us to keep track of the last node in the list.
Both are simple pointers to a node (in our case ListNodePtr).
}
var
head,tail : ListNodePtr;
node1,node2,node3,node4: ListNode;
count: integer;
{Init the linked list}
procedure InitLinkedList;
Begin
new(head);
new(tail);
(* **Remove comments from this code to see problems in final output**
head:=nil;
tail:=nil;
*)
node1.key:=10;
new(node1.NodePtr);
node1.NodePtr:=nil;
head^:=node1;
tail^:=node1;
writeln('head key is now: ',head^.key);
node2.key:=20;
new(node2.NodePtr);
node2.NodePtr:=nil;
head^.NodePtr^:=node2;
tail^:=node2;
writeln('head key is now: ',head^.key);
writeln('tail key is now: ',tail^.key);
writeln('node1 key is now: ',node1.key);
writeln('node2 key is now: ',node2.key);
readln;
end;
begin
InitLinkedList;
end
.