java - 为什么链表中的head是变化的?
问题描述
我试图在链表的末尾插入一个节点。我参考了指向头部的方法。然后我将头部移动到链表的最后一个,然后添加了一个新节点。
public class InsertNode {
public static void main(String[] args) {
SinglyNode head = new SinglyNode(5);
head.next = new SinglyNode(3);
head.next.next = new SinglyNode(7);
// insert at the last
SinglyNode startAfterInsertion = insertSinglyNodeAtLast(head, 6);
printSinglyLinkedList(startAfterInsertion); // prints 5 3 7 6 which is fine
printSinglyLinkedList(head); // this prints 5 3 7 6 but prior to the insertopn method call, it was 7 6
}
// printing all the elements in the linked list
private static void printSinglyLinkedList(SinglyNode startAfterInsertion) {
System.out.println("\n\n");
while (startAfterInsertion != null) {
System.out.println(startAfterInsertion.data);
startAfterInsertion = startAfterInsertion.next;
}
}
private static SinglyNode insertSinglyNodeAtLast(SinglyNode head, int data) {
SinglyNode append = new SinglyNode(data);
append.next = null;
if (head == null) {
return append;
}
SinglyNode ref = head; // took a reference to the head so that I could be able to move head
while (head.next != null) { // to move the head till the end of the linked list
head = head.next;
}
head.next = append; // appended the new node at the last
printSinglyLinkedList(head); // printing head which prints 7 6
return ref; // ref should be 5 3 7 6
}
}
以下是我的输出: -
7
6
5
3
7
6
5
3
7
6
#insertSinglyNodeAtLast 和 main 方法中的“head”是如何修改的?
解决方案
您的循环结束head
而不是ref
. 改变
SinglyNode ref = head; //took a reference to the head so that I could be able to move head
while(head.next!=null) { //to move the head till the end of the linked list
head =head.next;
}
head.next = append; //appended the new node at the last
到
SinglyNode ref = head; //took a reference to the head so that I could be able to move head
while(ref.next!=null) { //to move the head till the end of the linked list
ref =ref.next;
}
ref.next = append; //appended the new node at the last
进而
return ref;
应该
return head;
推荐阅读
- druid - 如何使用德鲁伊在 apache 超集中设置指标“HLLSketchMerge”
- python - 从数据集中获取列名
- c# - 如何对 IQueryable 中的派生列进行排序
- julia - 我们如何在 Julia 语言中表示 Python/numpy 函数“zeros_like”
- botframework - 自适应卡片显示在 cortana 频道上不显示,但在团队和模拟器上运行良好
- python - Need to extract all links from script tag HTML Python
- javascript - Sass 中的三和号
- angular - Angular-cli 和 Ckeditor4 自定义构建
- python - 将原始硬盘映像从 S3 存储桶转换为 EC2 映像
- c# - 打开 OpenFileDialog 以更改 PropertyGrid 控件中的属性值?