我有一個問題,理解指針的行爲設置爲零在帕斯卡。我使用渦輪pascal 7.0。 看來,當我設置兩個指針頭,尾部爲零...他們似乎總是指向未來相同的值,即使他們被分配到不同值。零指針帕斯卡爾
在下面的代碼中,當我註釋掉問題區域並獲得預期結果時。
當我從這兩行刪除註釋 head:= nil; tail:= nil;
當取消引用時,'head'指針似乎總是將'tail'指針的值賦予給它。任何見解提供將不勝感激。
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
.
如果您的'更新的解決方案'仍然有錯誤,然後描述它們。否則將其作爲自我回答發佈。 –
對不起,我剛剛看到這個回覆。我會等待進一步的答覆,然後做你的建議。 –