N Monkeys to choose the King, the method of election is as follows: All monkeys according to the ... n number and in order to enclose in a circle, from the 1th monkey, starting from 1 count, reporting m, the monkey jumped out of the circle, the next monkey from 1 began to count, so the cycle, until a monkey in the circle, the monkey is the king.
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct SNODE
{
int data;
struct Snode *next;
} Lnode;
void Houzi (int n,int k)
{
Lnode *p,*lq,*head,*s,*pre; P: Current node. Head: First node. Pre: The previous node of the current node.
head= (Lnode *) malloc (sizeof (Lnode));
head->next=head;
head->data=0;
P=head;
p->data=1;
p->next=p;
for (int i=2;i<=n;i++)
{
lq= (Lnode *) malloc (sizeof (Lnode));
lq->data=i;
lq->next=p->next;
p->next=lq;
p=p->next;
}
P=head;
Pre=head;
while (N!=1)
{for
(int i=1;i<k;i++)
{
p=p->next;
cout<<p->data<< "";
}
cout<<endl<<p->data<< "Outs" <<endl;
while (pre->next!=p) //determines the previous node of the delete node for deletion.
pre=pre->next;
pre->next=p->next;
s=p;
p=p->next;
Free (s);
n--;
}
cout<< "Last node:" <<p->data<<endl;
}
int main ()
{
Houzi (8,3);
}
Joseph Question.
WORKAROUND: Establish a circular linked list with n nodes and no head nodes to determine the position of the first person to be counted. Continuously removes nodes from the linked list until the list is empty.
Also needs to be done: single-linked list inversion, the single-linked list traversal once to find the middle value. Write it down first.