约瑟夫问题,我的代码为什么输出只有一个1

#include <iostream>

using namespace std;


typedef struct linknode

    {

        int value;

        struct linknode *next;

    }linknode,*linklist;


linklist createcycle(int total)

    {

        int index = 1;

        linklist prev = NULL,curr = NULL,head = NULL;

        head = new linknode;

        head->value = index;

        prev = head;

        for(;index < total;)

        {

            curr = new linknode;

            curr->value = ++index;

            prev->next = curr;

            prev = curr;

        }

        prev->next = head;

        return head;

    }


void run(int total,int tag)

    {

        linklist node = createcycle(total);

        linklist curr = node,prev = NULL;

        while (curr == curr->next)

        {


            for(int i = 0;i < tag-1;++i)

            {

                prev = curr;

                curr = prev->next;

            }

            cout<<curr->next->value<<"->";

            curr->next = curr->next->next;

            delete curr->next;

            prev = curr;

            curr = prev->next;

        }

        cout<<curr->value<<endl;

        delete curr;


    }


int main()

{

    run(41,3);

    return 0;

}


Lornsoul
浏览 1733回答 1
1回答

Lornsoul

已解决,抱歉问了个傻问题,现代码void run(int total,int tag)    {        linklist node = createcycle(total);        linklist curr = node,prev = NULL;        while (curr != curr->next)        {            for(int i = 0;i < tag-1;++i)            {                prev = curr;                curr = prev->next;            }            cout<<curr->value<<"->";            prev->next = curr->next;            delete curr;            curr = prev->next;        }        cout<<curr->value<<endl;        delete curr;    }
打开App,查看更多内容
随时随地看视频慕课网APP