c++ - 链表没有正确循环

标签 c++ list

<分区>

这是我的代码:

void setUpEachFlechette(int numFlechettes){

int i = 0;
int totalNum = 0;

Flechette* next;
Flechette* head;
Flechette* pEnd;
Flechette* temp;

    while(numFlechettes != i){

        double x = getRandomNumberX();
        double y = getRandomNumberX();
        double z = getRandomNumberZ();


         if(i != 0)
          temp = next;

         next = new Flechette;

         next->setXYZ(x, y, z);

         if(i == 0)
            head = next;
         else
          next->link = temp;

         i++;

         next->display();

    }


 cout<<"\nThe total number of flechettes is "<<totalNum<<endl<<endl;

 char yes = NULL;

 cout<<"Ready? ";
 cin>>yes;

 i = 0;

 next->link = NULL;
 next = head;
 while(next != NULL){

    next->display();
    next = next->link;

    i++;

 }

出于某种原因,当我遍历链表时,它只显示列表中的前 4 个节点,并继续重复前四个节点。我也无法让它以 null 正确结束,所以我可以通过 while(next != null) 循环运行它。我想知道为什么我的编码没有遍历所有的 Flechettes?作为引用,它应该循环遍历 20 个不同的飞弹,而不仅仅是循环“i”次 4 个飞弹。

我认为这些功能是不言自明的。如果他们不告诉我,我会向您解释。

最佳答案

您没有在打印前修改变量 totalNum。我也认为代码应该是这样的

void setUpEachFlechette(int numFlechettes){

int i = 0;
int totalNum = 0;

Flechette* next;
Flechette* head;
Flechette* pEnd;
Flechette* temp;
srand (time(NULL));
    while(numFlechettes != i){

        int x = rand();
        int y = rand();
        int z = rand();


         if(i != 0)
          temp = next;

         next = new Flechette;

         next->setXYZ(x, y, z);

         if(i == 0)
            head = next;
         else
          temp->link = next;

         i++;

         next->display();

    }

totalNum = numFlechettes;
 cout<<"\nThe total number of flechettes is "<<totalNum<<endl<<endl;

 char yes;

 cout<<"Ready? ";
 cin>>yes;

 i = 0;

 next->link = NULL;
 next = head;
 while(next != NULL){

    next->display();
    next = next->link;

    i++;

 }
}

在您的原始代码中,head 节点将是最后一个节点,head->next 将是 NULL

我希望您在 Flechette 的构造函数中使用 NULL 正确初始化成员变量 link

关于c++ - 链表没有正确循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994582/

相关文章:

html - 从Go中的HTML响应解析逗号分隔列表

java - 在 c++/java 中创建 sql 查询?

c++ - 在 XCode 中使用 C++ 代码

java - 在Java中使用泛型实现一个接受int和double并返回sum的列表

python - 如何在Python中将字符串日期列表转换为日期时间

r - 需要在R中逐行绑定(bind)列表数据

c++ - 如何显示图的邻接表的元素?

c++ - 确定一个位置在封闭哈希中是否空闲

c++ - 错误 : expected unqualified-id before ‘.’ token

c++ - 使用带有 COM 接口(interface)的 STL 智能指针