问题描述
我总是得到空值。我是这种语言的初学者。谢谢您的理解。
class Node{
int data;
Node next;
Node(int value){
data = value;
}
}
void addNode(Node headNode,int aValue){
Node newNode = new Node(aValue); //creating new node
newNode.next = headNode; // pointing the next to headNode
headNode = newNode; // updating the head Node
}
void main(){
Node head = Node(1);
addNode(head,2);
addNode(head,3);
print(head.next.data); //here I always get null
}
您的帮助将不胜感激。
解决方法
请考虑在其中更新headNode
的值。您到底要分配什么?
headNode
具有功能范围,这意味着它仅存在于addNote
功能中。同样,head
函数中的main
也具有函数作用域,因此只能在您的主函数中访问。
似乎您正在尝试从head
内部更新addNode
,但这不是您要的。
一种可能的解决方案是从addNode
返回新创建的节点,并使用返回的值在head
函数中重新分配main
。看起来像这样:
Node addNode(Node headNode,int aValue){
Node newNode = new Node(aValue);
newNode.next = headNode;
return newNode;
}
void main(){
Node head = Node(1);
head = addNode(head,2);
head = addNode(head,3);
print(head.next.data);
}
还要考虑的另一件事:当执行到达程序末尾时,列表是什么样的?是[1] > [2] > [3]
还是[3] > [2] > [1]
吗?