The implementation of Joseph loop of C++ circular linked list

  • 2020-04-02 02:44:05
  • OfStack

This article shows the method of implementing Joseph ring in circular linked list in C++ in the form of an example. Specific methods are as follows:

The main function code is as follows:


#include <iostream>
using namespace std;

typedef struct student
{
 int data;
 struct student* next;
}node,*LinkList;
//Joseph ring
void printfList(LinkList head){

 LinkList p=head;
 if (head!=NULL)
 {

 do{
  cout<<p->data<<" ";
  p=p->next;
 }while(p!=head);//There was a problem here, with do-while
 cout<<endl;
 }
}
void Josephus(int n,int k,int m){
 int i=2;
 LinkList head=(LinkList)malloc(sizeof(node));
 head->next=head;
 head->data=1;
 LinkList pre=head;
 while(i<=n){
   LinkList p=(LinkList)malloc(sizeof(node));
 p->data=i;
 p->next=pre->next;
 pre->next=p;
 pre=p;
 i++;
 }
 printfList(head);

 LinkList mend=pre;
 int kk=0;
 while(kk!=k){
 mend=mend->next;
 ++kk;
 }//Find k starts
 
 while(n--){//All output
 int mm=1;
 pre=mend;//You have to give pre a new complex value every time otherwise the program will fail
 while(mm!=m){//Instead of the required number, the pointer moves forward one step at a time, mend points to the person reporting the number, and pre points to the previous one
  pre=mend;
  mend=mend->next;
  mm++;
 }
 pre->next=mend->next;//The first chain goes to the next ready to count
 cout<<mend->data<<endl;
 LinkList deletem=mend;
 mend=pre->next;//Mend points to the person reporting the number;
 free(deletem); //Finally delete
 }
}
int main(){
 Josephus(13,4,1);
 return 0;
}

Hope that the article described in the C++ programming to help you.


Related articles: