繁体   English   中英

需要帮助为 C++ 中的循环链表编码迭代器

[英]Need help coding iterator for a circular linked list in C++

所以我正在创建一个循环链表来解决作业的约瑟夫斯问题。 我的 C++ 课有一个非常糟糕的教授,我真的不知道如何用 C++ 做任何事情。 我正在尝试编写一个迭代器来遍历列表,但我不知道从哪里开始或如何实现它。 谁能给我关于如何开始编码的建议或建议?

它非常像std::list迭代器,除了结束迭代器是下一个指针是列表的头部,而不是当它是NULL 参考页面会告诉您应该实施什么。 底层表示将是一个指向列表节点的指针, operator*将返回对数据的引用, operator++将指针设置为next等。

或者,使用具有模块化算法的数组实现。

Josephus 问题是,如果 N 个人决定通过将自己安排在一个圆圈中并消除圆圈周围的每个第 M 个人来选举领导者,随着每个人退出,则关闭排名。 找出最后一个剩下的人。 这是这个问题在 C++ 中的一个非常简单的实现。

    #include<iostream>
    #include<stdio.h>
    #include<cstdlib>
    #include<stdlib.h>
    using namespace std;
    struct node
    {   int info;
        struct node *next;
    }arr[]={{rand(),arr+1},{rand(),arr+2},{rand(),arr+3},{rand(),arr+4},{30,arr}};
    typedef struct node* Node;
    void josephus(Node);
    int main()
    {
        josephus(arr);
        system("pause");
    }
    void josephus(Node head)
    {
        Node ptr,temp;
        int length=1,position,i;
        ptr=head;
        while(ptr->next!=head)
        {
           ptr=ptr->next;
           length++;
        }
        ptr=head;
        printf(" Enter the position at which element should get eliminated ");
        scanf("%d",&position);
        while(length>1)
        {
           i=1;
           while(i<position)
           {
               ptr=ptr->next;
               i++;
           }
           temp=ptr;
           ptr=ptr->next;
           free(temp);
           length--;
        }
         printf("\n Last Element Left is %d Its address is %u \n",ptr->info,ptr);
        }

有关更多详细信息,请访问-https ://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM