约瑟夫问题

#include<iostream>

using namespace std;

typedef struct student

{

       int data;

       struct student *next;

}node;

void JOSEPHUS(int k,int m)                          //创建单链表

{

       node *head,*p,*s;

       int x,cycle=1;

       head=(node *)malloc(sizeof(node));

       p=head;

       int n=0;

       while(cycle)

       {

             

              cout<<"请输入一直不为0的数,输入0则结束"<<endl;

              cin>>x;

              if(x!=0)

              {

                     s=(node *)malloc(sizeof(node));

                     s->data=x;

                     p->next=s;

                     p=s;

                     n++;

              }

              else cycle=0;

      

 

       }

       head=head->next;

              p->next=head;

 

       node *q,*temp;

       p=head;

       while(--k)

       {

              p=p->next;

       }

       while(n-->=1&&p!=NULL)

       {

              int i=m;

              while(--i)

              {

                     q=p;

                     p=p->next;

              }

              temp=p;

              p=p->next;

              q->next=p;

              cout<<temp->data<<endl;

              free(temp);

             

       }

       if(n==0)

       {

              free(p);

       }

}

int main()

{

      

JOSEPHUS(3,2);

}

posted on 2011-08-03 14:29  原来...  阅读(334)  评论(0编辑  收藏  举报

导航