我可以使用 while 或 for 循环来打印列表吗?

问题描述

[9,18,27]

在这里do-while 用于打印列表的元素。

在当前设置下,我可以使用 whilefor 循环来打印列表吗?

注意:我认为 #include <iostream> #include <string.h> namespace forward_circular_linked_list { typedef struct Node { std::string data; Node *nextNode; }Node; class ForwardCircularLinkedList { private: Node *head; public: ForwardCircularLinkedList() : head(nullptr) {} void AddItem(std::string data) { Node * newNode = new Node(); newNode->data = data; if(head == nullptr) { head = newNode; newNode->nextNode = head; } else{ Node * copyOfhead = head; while(copyOfhead->nextNode != head) { copyOfhead = copyOfhead->nextNode; } copyOfhead->nextNode = newNode;// process last node newNode->nextNode = head; } } void print() { Node * copyOfhead = head; do { std::cout<<copyOfhead->data; copyOfhead = copyOfhead->nextNode; }while(copyOfhead != head); } public: static void test() { ForwardCircularLinkedList list; list.AddItem("Hello"); list.AddItem(" "); list.AddItem("World"); list.AddItem("!"); list.print(); } }; } do-while 是不同的循环结构。

解决方法

是的,您可以使用 do-whilefor 循环。 但是 do-while 更自然,因为它在代码主体之后检查条件。

您有一个循环数据结构并且(大概)您想打印每个元素一次。 只做一轮盘旋。 do{...move circulator}while(compare with head) 有正确的逻辑。

CGAL 实现了“循环器”并且正是这样做的,它从“头部”开始做一些事情并递增循环器直到它再次成为头部。 请参阅 https://doc.cgal.org/latest/Circulator/classCirculator.html(滚动到示例)。

请注意该示例还在开始时检查 emptyness,但您可能需要。 (在我看来,循环缓冲区永远不会为空,但我接受其他意见。)


有了 while,您可以:

        Node * copyOfHead = head;

        do
        {
            std::cout<<copyOfHead->data;
            copyOfHead = copyOfHead->nextNode;
        }while(copyOfHead != head);

有了for,你可以拥有

        Node * copyOfHead = head;

        for(;;){
            std::cout<<copyOfHead->data;
            copyOfHead = copyOfHead->nextNode;
            if(copyOfHead == head) break;
        }

        for(Node * copyOfHead = head;;){
            std::cout<<copyOfHead->data;
            copyOfHead = copyOfHead->nextNode;
            if(copyOfHead == head) break;
        }

        for(Node * copyOfHead = head; ; copyOfHead = copyOfHead->nextNode){
            std::cout<<copyOfHead->data;
            if(copyOfHead->nextNode == head) break;
        }

or(利用循环体的计算结果为 bool:true)

        for(
            Node * copyOfHead = head;
            std::cout<<copyOfHead->data;
            copyOfHead = copyOfHead->nextNode
        ) if(copyOfHead->nextNode == head) break;

for 的主要优点是初始化,但仍然不值得。 您当然可以在循环外执行该步骤,但是您会重复代码等。

(不推荐,它甚至可能有一个错误)

        Node * copyOfHead = head;
        std::cout<<copyOfHead->data;
        copyOfHead = copyOfHead->nextNode;

        for(; copyOfHead != head ;copyOfHead = copyOfHead->nextNode){
            std::cout<<copyOfHead->data;
        }

所以,您有了,do-while 正是您想要的这种数据结构!而for(或while-only)正是您想要的。