[英]Why head in the linked list is changing?
我試圖在鏈表的末尾插入一個節點。 我參考了指向頭部的方法。 然后我將頭部移動到鏈表的最后一個,然后添加了一個新節點。
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
}
}
以下是我的output:-
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.