简体   繁体   English

循环双链表Java-说明

[英]Circular Doubly Linked List Java - Explanation

at the moment, I am programming a circular doubly linked list and my task is completed, but I have a slight problem in understanding the code 100%. 目前,我正在编写一个循环双链表,并且我的任务已完成,但是在理解代码100%时我有一个小问题。

This is the code: 这是代码:

if (counter == 0) {
        startpoint = newNode;
        startpoint.next = startpoint;
        startpoint.prev = startpoint;
        head = startpoint;
        currentNode = newNode;

    } else {
        newNode.prev = startpoint.prev;
        newNode.next = startpoint;
        startpoint.prev.next = newNode; <- this is, where I have problems
        startpoint.prev = newNode;
        head = startpoint;
        currentNode = newNode;
    }
    counter++;
}

The first part is completeley clear and just describes, that the first node (if there is no other node) is going to point on itself, when the next or first-method is called. 第一部分是完全清楚的,仅描述了当调用下一个或第一个方法时,第一个节点(如果没有其他节点)将指向自己。 After the else-statement, the first line describes that the first node can point to the second and the second to the previous node, right? 在else语句之后,第一行描述第一个节点可以指向第二个节点,第二个节点可以指向前一个节点,对吗? The second line after else just describes, that the last node points onto the first one. 后面的第二行仅描述了最后一个节点指向第一个节点。 The fourth line than describes, that the first node points onto the last node, if the prev-method is called and so the circle is closed. 第四行描述的是,如果调用了prev方法,则第一个节点指向最后一个节点,因此圆是闭合的。 But what exactly does the third line describes? 但是第三行到底描述了什么? The code definitely works. 该代码绝对有效。

Thank you for your time! 感谢您的时间!

Greets Dominik 向多米尼克致意

Your list is circular. 您的清单是循环的。

startpoint.prev is the element before the startpoint, so it's the last element of the list. startpoint.prevstartpoint.prev之前的元素,因此它是列表的最后一个元素。

Let's take an example, this is your list: A>B>C , you try to add D . 让我们举个例子,这是您的列表: A>B>C ,您尝试添加D

This line: startpoint.prev.next = newNode; 这行代码: startpoint.prev.next = newNode; will link the current last element ( C as A.prev == C ) to your new element. 会将当前的最后一个元素( CA.prev == C )链接到新元素。 ( C.next = D ) C.next = D

this line startpoint.prev = newNode; 这行startpoint.prev = newNode; will set the new element as the last element of the list ( A.prev = D ). 将新元素设置为列表的最后一个元素( A.prev = D )。

The code inserts newNode just before startpoint . 该代码在startpoint之前插入newNode The 3rd line of the else statement simply updates the node before the startpoint so that it's next field references the new node. else语句的第三行仅更新起点之前的节点,以便其next字段引用新节点。

To make it more clear, one can rewrite the line like this: 为了更加清楚,可以像这样重写该行:

    Node nodeBeforeStarpoint = startpoint.prev;
    nodeBeforeStartpoint.next = newNode; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM