Home > Back-end >  C language data structures: josephus problem of ring for help.
C language data structures: josephus problem of ring for help.

Time:10-18


Requirement please enter the number, contract number number, dequeue value is the number of ring, the starting position, and every few output,
Example: input 7 3 3 finally get 3627514
The code is as follows:

 # include 
# include

Typedef struct Lnode
{
int data;
Struct Lnode * next;
} Joseph;

Void Create_List (Joseph * L, int n)
{
int i;
Joseph * p, * s;

P=s=L;

for(i=2; i<=n; I++) {
S=(Joseph *) malloc (sizeof ());
S - & gt; Data=https://bbs.csdn.net/topics/i;
P - & gt; Next=s;
P=s;
}
P - & gt; Next=L;

}
Void Delete_List (Joseph * p, Joseph * q)
{
Q - & gt; Next=p - & gt; Next;
Free (p);
}


Void josephus (Joseph * L, int s, int m)
{
int length;
Length=sizeof (L) - 1;

Int I, j;
The static Joseph * p, * q, * Y.

P=L;

for(i=1; iIf (I==1) {
for(j=1; JP=p - & gt; Next;
}
Q=p - & gt; Next;
P - & gt; Next=q - & gt; Next;
Y - & gt; Data=https://bbs.csdn.net/topics/q-> data;
Y=Y - & gt; Next;
Free (q);
} else {
for(j=1; JP=p - & gt; Next;
}
Q=p - & gt; Next;
P - & gt; Next=q - & gt; Next;
Y - & gt; Data=https://bbs.csdn.net/topics/q-> data;
Y=Y - & gt; Next;
Free (q);
}

}

printf("\n");


Printf (" % 4 d \ n ", Y - & gt; The data);
return L;

}


Void main ()
{
Joseph * L=NULL;
Int m, n, s;
L=(Joseph *) malloc (sizeof ());
L - & gt; data=https://bbs.csdn.net/topics/1;
Printf (" please enter the number, contract number, dequeue value: \ n ");
The scanf (" % d % d % d ", & amp; N, & amp; S, & amp; M);
If ((m> 1000) | | (n> 1000))
Printf (" input the number of m, n illegal \ n ");
The else
If (s> N) printf (" input data is illegal! \n");
The else
{
Create_List (m, n);
Printf (" \ n ");
Josephus (L, s, m);
}
}


Run results with some debugging values are as follows:
  • Related