![](/img/trans.png)
[英]why am i getting this never ending loop while trying to print elements in singly linked list
[英]Can I use a while or for loop to print the list?
#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被用來打印列表的元素。
在當前設置下,我可以使用while或for循環來打印列表嗎?
注意:我正在考慮將do-while
和while
作為不同的循環結構。
是的,您可以使用do-while
或for
循環。 但是do-while
更自然,因為它檢查代碼主體之后的條件。
您有一個循環數據結構,並且(大概)您想打印每個元素一次。 只做一輪盤旋。 do{...move circulator}while(compare with head)
具有正確的邏輯。
CGAL 實現了“循環器”並確實做到了,它從“頭”開始做一些事情並增加循環器,直到它再次成為頭。 請參閱https://doc.cgal.org/latest/Circulator/classCirculator.html (滾動到示例)。
請注意,該示例還在開始時檢查是否為空,但可能是您想要的。 (在我看來,循環緩沖區永遠不會是空的,但我接受其他意見。)
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;
}
或(利用循環體的計算結果為 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
)正是你不想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.