为什么我们在循环链表中使用 Do While 而不是 While?

问题描述

例如我想在开始列表中添加一个元素:

public void add(int Data){
    //ignoring the possibility that the list is empty
    Node currentNode = head;
    do {
        currentNode = currentNode.getNext();
    } while (currentNode.getNext() != head);
    Node newNode = new Node(Data);
    newNode.setNext(head);
    currentNode.setNext(newNode);
    head = newNode;

如果我们在上面的代码中使用while循环会导致什么问题?

解决方法

正如我所看到的,您的示例代码是不正确的,在 while 的最后,currentNode 将是头部,但您需要在头部之前的节点处停止。

你的停止条件应该是:

...
}
while (currentNode.getNext() != head)

使用while循环就不会有问题。你需要做的就是从head之后的下一个节点开始,直到head之前的节点。

Node currentNode = head.getNext();
// @todo: test first if the currentNode is null 

while (currentNode.getNext() != head) {
   currentNode = currentNode.getNext()