【问题标题】:How do I restart a loop of a linked list? [closed]如何重新启动链表的循环? [关闭]
【发布时间】:2020-04-22 22:56:19
【问题描述】:

所以我想重新启动链表的循环以再次打印值,正如您在我的代码中看到的那样,如果我运行它,我只会有一次printf,因为它到达了列表的末尾,当第二个循环尝试转到列表时,指针已经在末尾,如何让它再次转到列表的开头?

void UC_show(L_uc_data *list, L_af_data *list1, FILE *fout)
{
    //int number_char=0;

    while (list) { // here its starts the loop of the principal list
        //Get length from names
        int n_char=strlen(list->uc_data.uc_name);
        printf("%d\n",n_char);
        fprintf(fout, "%d -> %s\n", list->uc_data.uc_number, list->uc_data.uc_name);
        while (list1) { // here it starts a loop of the secondary list
            fprintf(fout, "%d - %d - %d - %d - %d - %s\n", list1->number_uc, list1->start, list1->end, list1->done, list1->n_sessions, list1->af_name);
            list1 = list1->next;
        }
        list = list->next; // it goes to the next entry of the principal list the loop of the second list should start from the beginning
    }

}

【问题讨论】:

  • 您只需将原始值保存在某处
  • 将原始引用存储在临时变量中。 L_uc_data *temp = list 然后使用它恢复您的列表。理想情况下,应该通过临时指针进行迭代并保持初始指针不变,但是是的,你可以做其他方式。
  • 您介意添加main 以便我们进行测试吗?
  • 已经使用@stanle 输入解决了问题,您需要的不仅仅是主要的测试,您需要所有的结构

标签: c function loops data-structures linked-list


【解决方案1】:

您可以将给定的地址复制到一个虚拟指针中。使用该指针遍历您的列表并在使用后丢弃它!除非必要,否则更改参数中给出的值通常是个坏主意:)

【讨论】:

  • 你推荐一个没有虚拟指针的客场吗?我想使用循环来搜索值
  • 虚拟指针仍然指向与原始指针相同的地址,所以不用担心。您仍然可以使用该指针找到您的数据。请记住,指针只是一个地址,您可以将地址复制到任何地方,它仍然会指向正确的位置。
  • @RGO,stanle 的意思类似于L_af_data *af_node = list1; while (af_node) { ...; af_node = af_node->next; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2018-12-24
  • 2017-11-24
  • 2010-10-04
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多