C++循环链表之约瑟夫环的实现方法
本文实例形式展示了C++实现循环链表中约瑟夫环的方法,分享给大家供大家参考之用。具体方法如下:
主要功能代码如下:
#include<iostream>
usingnamespacestd;
typedefstructstudent
{
intdata;
structstudent*next;
}node,*LinkList;
//约瑟夫环
voidprintfList(LinkListhead){
LinkListp=head;
if(head!=NULL)
{
do{
cout<<p->data<<"";
p=p->next;
}while(p!=head);//这里出现过问题,用do-while
cout<<endl;
}
}
voidJosephus(intn,intk,intm){
inti=2;
LinkListhead=(LinkList)malloc(sizeof(node));
head->next=head;
head->data=1;
LinkListpre=head;
while(i<=n){
LinkListp=(LinkList)malloc(sizeof(node));
p->data=i;
p->next=pre->next;
pre->next=p;
pre=p;
i++;
}
printfList(head);
LinkListmend=pre;
intkk=0;
while(kk!=k){
mend=mend->next;
++kk;
}//找到k个开始
while(n--){//要全部输出
intmm=1;
pre=mend;//每次都要给pre从新复值否则程序错误
while(mm!=m){//不是要求的数,指针每次往前推一步,mend指向报数的人,pre指向前一个
pre=mend;
mend=mend->next;
mm++;
}
pre->next=mend->next;//前一个链到下一个准备报数的
cout<<mend->data<<endl;
LinkListdeletem=mend;
mend=pre->next;//mend指向报数的人;
free(deletem);//最后删除
}
}
intmain(){
Josephus(13,4,1);
return0;
}
希望本文所述对大家的C++程序设计有所帮助。