N0.3

约瑟夫环问题

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();
           

        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值