首页 > 解决方案 > 为什么链表中的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”是如何修改的?

标签: javaalgorithmdata-structureslinked-listinsert

解决方案


您的循环结束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;

推荐阅读