为什么链接列表中的头在更改



我正试图在链表的末尾插入一个节点。我引用了一个指向头部的方法。然后,我将标题移到链表的最后一个,然后添加了一个新节点。

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("nn");
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;

相关内容

  • 没有找到相关文章

最新更新