约瑟夫环

约瑟夫(Joseph)问题的一种描述是:编号为123,…,nn个人按顺时针方向围坐一圈。每人持有一个密码(正整数)。一开始任选一个正整数作为报数上限值m,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数,令其出列,将他的密码作为新的m值,从他在顺时针方向上的下一个人开始重新报数,如此下去,直到所有人全部出列为止。试设计一个程序求出出列顺序。

    实验要求

利用无头结点的单向循环链表存储结构模拟此过程,按照出列的顺序打印出各人的编号。

测试数据:

    m的初值为20n=7,7个人的密码依次为:3172484,首先m值为6(正确的出列顺序应为6147235

 实验提示:

    程序运行后,首先要求用户指定初始报数上限值,然后读取各人的密码,可设n<=30,此题所用的循环链表中不需要“头结点”,请注意空表和非空表的界限。


#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
    int key;
	int order;
	struct node *next;
}Node;

void Init_Node(Node *node);
Node* Create_List(int listLength);
void Function(Node *head,int maxKey,int listLength);//实现功能的函数
void Print(Node *head);
Node* FindTail(Node* head,int listLength);
void main()
{
	Node *listA;
	int maxKey=20,listLength;
	printf("请输入报数的上限值m和总人数n\n");scanf("%d%d",&maxKey,&listLength);
    listA=Create_List(listLength);
    Print(listA);
	Function(listA,maxKey,listLength);
}

void Init_Node(Node *node)
{
	node->next=NULL;
	node->order=0;
	node->key=0;
}

Node* Create_List(int listLength)
{
	printf("*********正在申请一个长度为%d的不带头结点的单向循环链表*********\n",listLength);
	Node *head,*tail,*newNode,*node_del;
	int key,i=1;
	head=(Node *)malloc(sizeof(Node));if(head==NULL) {printf("申请内存失败\n");return NULL;}
    tail=head;tail->next=NULL;
    while(listLength--)
	{
	    newNode=(Node *)malloc(sizeof(Node));Init_Node(newNode);
		newNode->order=i;
		printf("请输入第%d个节点的密码",i++);
        scanf("%d",&key);newNode->key=key;
		tail->next=newNode;
		tail=newNode;
	}
	node_del=head;
	head=head->next;
	tail->next=head;
	free(node_del);
	printf("*********单向循环链表创建完毕*********\n");
	return head;
}

void Function(Node *head,int maxKey,int listLength)
{
    Node *node,*node_del;node=head;int count=0,freeTimes=0;
	printf("遍历中......\n所有人的出列顺序为\n");
	node_del=head;
	node=FindTail(head,listLength);
	while(node->next!=NULL)
	{
		node_del=node->next;
		count++;
        if(count==maxKey)    
		{          
			count=0;                                          
			maxKey=node_del->key;
			printf("%d  ",node_del->order);                                                   
			node->next=node_del->next;
			free(node_del);freeTimes++;
		}
		else node=node->next;
		if(freeTimes==listLength)break;
	}
	printf("出列完毕\n");
}

void Print(Node *head)
{
    Node *node;
	node=head;int loopTimes=-1;
	while(node!=NULL)
	{
		if(node==head)loopTimes++;
		if(loopTimes==1)break;
	    printf("第%d个人的密码是%d\n",node->order,node->key);
		node=node->next;
	}
	printf("Print完毕\n");
}

Node* FindTail(Node* head,int listLength)
{
	Node *node;node=head;
	listLength--;
    while(listLength--)
	{
		node=node->next;
	}
	return node;
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值