The classic problem of the list--The monkey Choose King

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.