Chinaunix首页 | 论坛 | 博客
  • 博客访问: 108866
  • 博文数量: 40
  • 博客积分: 2058
  • 博客等级: 大尉
  • 技术积分: 409
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-07 16:49
文章分类

全部博文(40)

文章存档

2011年(3)

2010年(17)

2009年(14)

2008年(6)

我的朋友

分类: C/C++

2009-03-10 19:45:47

/*  HELLO.C -- Hello, world */

/*約瑟夫环问题*/

#define N 20
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct Node
{
    int data; /*圈中人的序号*/
    int sec; /*每个人的密码*/
    struct Node *next;
} Node, *Linklist;
Linklist creat(int n) /*n为圈中的人数*/
{
    Linklist Head ;
    Node *s,*p;
    int i;
    Head=p=(Linklist)malloc(sizeof(Node));
    p->data=1;
    printf("\nplease input the password of number :");
    scanf("%d",&p->sec);
    for(i=1;i<n;i++)
    {
        s=(Linklist)malloc(sizeof(Node));
        s->data=i+1;
        printf("please input password of number %d:",i+1);
        scanf("%d",&s->sec);
        p->next=s;
        p=s;
    }
    p->next=Head;
    return Head;

}
int *quit(int n,int m,Linklist L) /*n为圈中的人数,m为开始报数的上限值,L为创建好的连环*/
{
    int num[N];
    int i,j,k=0;
    /*Linklist Head;*/
    Node *p,*s;
    j=m-1; /*j为要退出人的密码*/
    p=L;
    while(k<n)

    {
        for(;j>1;j--) /*在环中寻找要退出的人的前一个人的节点*/

            p=p->next;

        s=p->next;

        num[k]=s->data; /*s为要要退出的节点*/
        j=s->sec;
        p->next=s->next;
        free(s);
        k++;
    }

    return num;
}
int main()
{

    Linklist L;
    int *p;
    int n,m;
    int i;
    printf("intup the people and frist number :");
    scanf("%d %d",&n,&m);
    L=creat(n);
    p=quit(n,m,L);
    for(i=0;i<n;i++) /*打印退出序号*/
    printf("%d ,",*p++);
    getch();
    return 0;
}


阅读(721) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~