【问题标题】:Understanding insertion in a linked list了解链表中的插入
【发布时间】:2020-06-20 17:47:29
【问题描述】:

我无法理解如何在链表中插入。我在网上找到了一些示例,但我似乎无法 100% 理解它。在这段代码中,我将 cmets 放在了我认为发生的事情上代码,以及我正在努力的。一些帮助将不胜感激。谢谢!

    private static final class Node {
        final Person person;
        Node next;

        Node(Person person) {
            this.person = person;
        }
    }

   public boolean insert(Person person) {
        Node n = new Node(person);
        //insert as the first element
        if (head == null) {
            head = n;
            size++;
            return true;
        }

        Node current = head;
        Node prev = null;
        int comparison;

        while (current != null) {
            //until the list is empty compare 
            comparison = person.name.compareTo(current.person.name);
            //that person already exists
            if (comparison == 0) {
                return false;
            } else if (comparison > 0) { 
                //if the next spot in the list is empty place the person there
                if (current.next == null) { 
                    current.next = n;
                    break;
                }
            } else { 
            //this is the part I dont understand
                if (prev == null) { 
                    Node oldHead = head;
                    head = n;
                    head.next = oldHead;
                    break;
                }
                //dont understand this either
                prev.next = n;
                n.next = current;
                break;
            }
            //keep moving through the list
            prev = current;
            current = current.next;
        }
        size++;
        return true;
    }

【问题讨论】:

    标签: java methods linked-list


    【解决方案1】:

    根据您在代码中所做的所有比较,这似乎是一个排序的链表,而不是一个普通的链表。

    这段代码是说,如果插入的值小于头部,我们希望这个新值是头部,原始头部是列表中的第二个值。因此 oldHead 是 head 的一个引用变量,只是为了临时保存该值。之后,head = n 只是将头(也就是列表中的第一个节点)设置为新节点,所以现在第一个节点就是被插入的节点。然后 head.next = oldHead 将列表中的下一个值设置为等于列表的原始头部。现在插入的值是列表中的第一个值,原始头部是列表中的第二个值。

    if (prev == null) { 
            Node oldHead = head;
            head = n;
            head.next = oldHead;
            break;
    }
    

    这段代码只是设置链接,因此所有变量都链接在一起。

    //dont understand this either
    prev.next = n;
    n.next = current;
    break;
    

    【讨论】:

    • 哦,不好意思,我没说它是排序链表,对不起!谢谢你的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多