鱼C论坛

 找回密码
 立即注册
查看: 2678|回复: 2

[技术交流] 关于Josephus问题2

[复制链接]
发表于 2015-3-27 16:53:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>
#include <malloc.h>
struct Node
{
    int data;
    struct Node *prior, *next;
};

void CreateLoopList(struct Node **, int);
void SolveJosephus(struct Node *);
void ListTraverse(struct Node *);
void main()
{
    int n =10;
    struct Node *head = NULL;
    CreateLoopList(&head, n);
    ListTraverse(head);
    SolveJosephus(head);
}

void CreateLoopList(struct Node **head, int n)
{
    int i = 1;
    struct Node *p, *q;
    *head = (struct Node*)malloc(sizeof(struct Node));
    p = *head;
    q = (struct Node *)malloc(sizeof(struct Node));
    p->next = q;
    p = q;
    p->data = i++;
    while(i<=n)
    {
        q = (struct Node *)malloc(sizeof(struct Node));
        p->next = q;
        q->prior = p;
        p = q;
        p->data = i++;
    }
    p->next = (*head)->next;
    (*head)->next->prior = p;
}

void ListTraverse(struct Node *head)
{
    struct Node *p, *q;
    p = q = head->next;
    do
    {
        printf("%d ", p->data);
        p = p->next;
    }while(p!=q);
    printf("\n\n");
    do
    {
        printf("%d ", q->prior->data);
        q = q->prior;
    }while(q!=p);
    printf("\n");
}

void SolveJosephus(struct Node *head)
{
    int i=1, j, m;
    struct Node *p , *q;
    q = head->next;
    p = q->prior;
    while(p!=p->next)
    {
        printf("请输入第%2d个人的密码作为报数的上限值: \n", i);
        scanf("%d", &m);
        j = 1;
        while(j++%m)
        {
            p = p->next;
        }
        q = p->next;
        p->next = q->next;
        printf("第%2d个人出队\n", q->data);
        i = q->data;
        free(q);
    }
    printf("第%2d个人出队\n", p->data);
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-5-26 01:32:39 | 显示全部楼层
:shock:
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-6-5 17:09:40 | 显示全部楼层
{:1_1:}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-11 18:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表