【发布时间】:2017-11-20 07:22:07
【问题描述】:
所以,我研究了链表并创建了这个插入方法。
private void insert(Node head, int data)
{
Node node = new Node(data);
Node first = head;
if(first == null)
{
head = node;
}
else
{
node.nextLink = first;
head = node;
//System.out.println(node.data);
}
}
还有这个遍历方法
public void traversingLinkedList(Node head)
{
Node current = head;
while(current != null)
{
int data = current.data;
System.out.println(data);
current = current.nextLink;
}
}
但是当我插入它时它没有显示节点。 当我取消注释方法插入中的打印行时,节点数据显示。
例如,
存在的链表是 10 -> 20 -> 30
使用 insert(head,4) 之后 我仍然得到 10 -> 20 -> 30
虽然在方法插入时我取消选中打印方法 它显示第一个节点数据为 4
但是在遍历时没有显示!
为什么?
【问题讨论】:
-
您似乎在前面插入元素。你的 insert 方法不应该返回新的 head 元素? (是,节点?)
-
应该的。我发现的一个错误是在 main 方法中我设置 Node head = ob1 所以,每次它只取 head = ob1 (即 10)。如何解决这个问题?
-
你的 insert 方法应该返回新的 head 值,这应该更新调用函数的 head 值。
标签: java linked-list