标签:
有N个人围一圈依次报数,数到3的倍数的人出列,问当只剩一个人时他原来的位子在哪里?
/*约瑟夫环问题---单向循环链表实现*/
/**********************************/
/**********Date:2015.3.11*********/
/*********author:xiaozhi xiong***/
/*******************************/
#include"stdio.h"
#include"stdlib.h"
struct node
{
int data;
struct node *next;
};
struct node *head;//链表的头节点
/************创建循环链表**************/
/**********input:链表头节点,人数******/
/************return:无*****************/
/************author:xiaozhi xiong******/
/**************************************/
void CreateLink(struct node *head,int len)
{
struct node *newNode,*parNode;
int i;
head->data=1;
parNode=head;
for(i=2;i<=len;i++)
{
newNode=(struct node *)malloc(sizeof(struct node));
newNode->data =i;
newNode->next =NULL;
parNode->next =newNode;
parNode=newNode;
}
newNode->next=head;
}
/************输出循环链表**************/
/**********input:链表头节点************/
/************return:无*****************/
/************author:xiaozhi xiong******/
/**************************************/
void DisplayLink(struct node *head)
{
struct node *p;
if(head==NULL)
{
printf("链表为空\n");
return;
}
p=head;
printf("循环链表:\n");
while(p->next!=head)
{
printf("%d ",p->data );
p=p->next ;
}
printf("%d ",p->data );
}
/************约瑟夫环******************/
/**********input:链表头节点************/
/**********input:链表长度**************/
/**********input:第几个开始计数********/
/************return:无*****************/
/************author:xiaozhi xiong******/
/**************************************/
void Jose(struct node *head,int len,int num)
{
int i;
struct node *startNode,*endNode,*midNode;
startNode=head;
if(num>len)
{
printf("输入有误,不能从第%d个开始",num);
return;
}
if(num>1)
{
for(i=2;i<=num;i++)
startNode=startNode->next ;
}
midNode=startNode->next ;
endNode=midNode->next;
while(!(startNode==midNode&&midNode==endNode))
{
//删除第三个节点
midNode->next =endNode->next ;
//重新分配节点
startNode=endNode->next ;
midNode=startNode->next ;
endNode=midNode->next;
}
printf("最后一个节点为%d",startNode->data );
}
void main()
{
head=(struct node *)malloc(sizeof(struct node));
head->next =NULL;
CreateLink(head,4);
DisplayLink(head);
Jose(head,4,1);
getchar();
}
标签:
原文地址:http://blog.csdn.net/jxxiongxiaozhi/article/details/44202351