约瑟夫环问题
C:
#include "stdio.h"
#define NULL 0
main()
{
struct node
{
int data;
struct node *next;
};
int n,m,k,i;
struct node *head,*p,*r;
//n为总共的人数,k是从第几个开始数,每数m个出局一个人
printf("input the totle number,the start number and the space/n");
scanf("%d,%d,%d",&n,&k,&m);
//输入不合法从新输入
while(k>n)
{
printf("error;the start number cannot bigger than the totle number!/n");
printf("input the totle number,the start number and the space/n");
scanf("%d,%d,%d",&n,&k,&m);
}
//建立节点并赋值
head=NULL;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=i;
//定义头
if(head==NULL)
{
head=p;
}
//将两个节点连接
r->next=p;
r=p;
}
//j将尾节点和头连接形成循环链表
p->next=head;
//找到第K个点
for(i=0;i<k;i++)
{
r=p;
p=p->next;
}
while(p->next!=p)
{
//隔M个节点就打印并从链表中删除
for(i=0;i<m-1;i++)
{
r=p;
p=p->next;
}
r->next=p->next;
printf("%d ",p->data);
free(p);
p=r->next;
}/**/
printf("%d ",p->data);
}
相比之下还是C#比较好用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace josephus
{
class Program
{
static void Main(string[] args)
{
IList<int> ln = new List<int>();
int n,k,m;
int i;
//输入参数
Console.WriteLine("input the totle number");
n=Console.Read();
Console.WriteLine("input the start number");
k = Console.Read();
Console.WriteLine("input the space");
m = Console.Read();
for (i = 1; i <= n; i++)
{
ln.Add(i);
}
i = k -1;
//是用LIST所以不能循环,就用取余(i % ln.Count)的结果找到超出范围所对应的元素打印并删除
//比如只有5个元素,但要数8个,如果从第一个开始数,第八个就对应着(8%5)第三个元素
do
{
i = i + m - 1;
if (i >= ln .Count )
{ i = i % ln.Count; }
Console.WriteLine("{0} ", ln[i]);
ln.RemoveAt(i);
} while (ln.Count != 0);
Console.ReadLine();
}
}
}