约瑟夫环(链表)

#include “iostream”;
using namespace std;

int n=41;
int k=3;
int count=1;//用于计数

typedef structnode{    //链表结点结构体
 intdata;   //链表结点成员:数值
 struct node *next; //链表结点成员:后续结点指针
}LNode,*Linklist;

Linklist head;

Linklist creatlinklist(){
   Linklistp,r;  //r为尾指针,p为临时指针
   head =NULL;
   int i;
                    
  for(i=0;i
    p=new LNode;
  p->data = i+1;
  p->next =NULL;

  if((!head)) {
  head = p;  
  }
  else { 
  r->next =p;   
  } 
  r = p;
    }
     if (i=n)
   {
   r->next=head;
  }  
     return head;
    }

 void main(){
  creatlinklist();
  Linklistp;//临时指针  用于插入
  p=head;
  Linklist r;//尾指针
  r=p;
  int lastnumber=n;
  for (inti=1;i<=n-1;i++)
  {
   r=r->next;
  }

  while(lastnumber>k-1){
   if(count==3)
   {
    if(p==head)
    {
     head=head->next;
     r->next=head;
     p=head;
    }
    else
    {
     p=p->next;
     r->next=p;
    }
    count=1;
    lastnumber–;
   }
   else
   {
    p=p->next;
    r=r->next;
    count++;
  }
  }
  cout<<p->data<<” “<<p->next->data<<endl;
    
    }

 

    原文作者:约瑟夫环问题
    原文地址: https://blog.csdn.net/sporte/article/details/17472949
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞