首页 > 编程语言 > 详细

用线性表来解决约瑟夫环问题(C语言)

时间:2015-05-03 17:31:30      阅读:261      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>
#include<stdlib.h>
#define OK 1;
#define ERROR 0;
typedef int Status;
typedef int Elemtype;
typedef struct Cnode{
    Elemtype data;
    struct Cnode *next;
}CNode;
CNode *joseph;
Status Create_clist(CNode *clist,int n){
    CNode *p,*q;
    int i;
    clist=NULL;//NULL=0for (i = n; i >=1; i--)
    {
        p=(CNode*)malloc(sizeof(CNode));
        if (p==NULL)
        {
            return -1;//存储空间分配失败
        }
        p->data=i;
        p->next=clist;
        clist=p;
        if (i==n)
        {
            q=p;
        }
    }
    q->next=clist;
    joseph=clist;
    return OK;
}
Status Joseph(CNode *clist,int m,int n,int k){
int i;
CNode *p,*q;
if (m>n)
{
    return ERROR;
}
if (!Create_clist(clist,n))
{
    return ERROR;
}
p=joseph;
for ( i = 1; i <m; i++)
{
    p=p->next;
}
while (p)
{
    for ( i = 1; i <k-1; i++)
    {
        p=p->next;
    }
    q=p->next;
    printf("%d\n",q->data);
    if (p->next==p)
    {
        p=NULL;
    }else
    {
        p->next=q->next;
        p=p->next;
        free(q);
    }
}
clist=NULL;
}
void main(){
    int m,n,k,i;
    CNode *clist;
    clist =NULL;
    printf("\n请输入围坐在圆桌周围的人数n:");
    scanf("%d",&n);
    printf("\n请输入第一次开始报数人的位置m:");
    scanf("%d",&m);
    printf("\n请输入你希望报数到第几个数的人出列?:");
    scanf("%d",&k);
    Create_clist(clist,n);
    printf("\n出列的顺序如下:\n");
    Joseph(clist,m,n,k);
    system("pause");
}

用线性表来解决约瑟夫环问题(C语言)

原文:http://blog.csdn.net/a819721810/article/details/45459631

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!