Joseph问题
1.Joseph描述:
原始的Joseph问题的描述如下:有n个人围坐在一个圆桌周围,把这n个人依次编号为1,…,n。从编号是start的人开始报数,数到第num个人出列,然后从出列的下一个人重新开始报数,数到第num个人又出列,…,如此反复直到所有的人全部出列为止。比如当n=6,start=1,num=5的时候,出列的顺序依次是5,4,6,2,3,1。
2.instance analysis
#include <stdio.h>
#include <stdlib.h>
typedef int DATATYPE;
typedef struct node
{
DATATYPE data;
struct node *next;
}LoopList;
LoopList *create_empty_looplist()
{
LoopList *head;
head = (struct node *)malloc(sizeof(struct node));
head->next = head;
return head;
}
int insert_head_looplist(LoopList *head,DATATYPE data)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = head->next;
head->next = temp;
return 0;
}
LoopList *cut_head_looplist(LoopList *head)
{
struct node *p = head;
//找到尾部节点
while(p->next != head) p = p->next;
//删除头节点
p->next = head->next;
free(head);
head = NULL;
return p->next;
}
int printf_looplist(LoopList *head)
{
struct node *p = head->next;
while(p != head)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
return 0;
}
int _printf_looplist(LoopList *head)
{
struct node *p = head->next;
printf("%d ",head->data);
while(p != head)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
return 0;
}
void joseph(int n,int k,int m)
{
int i = 0;
struct node *temp,*p;
LoopList *L = create_empty_looplist();
for(i = n;i > 0;i --)
{
insert_head_looplist(L,i);
}
p = cut_head_looplist(L);
//找到第K个人
for(i = 0;i < k -1;i ++)
{
p = p->next;
}
while(p->next != p)
{
//找到要删除节点的前一节点
for(i = 0;i < m - 2;i ++)
{
p = p->next;
}
//删除
temp = p->next;
printf("%d ",temp->data);
p->next = temp->next;
free(temp);
//从一个节点开始计数
p = p->next;
}
printf("%d\n",p->data);
free(p);
return;
}
int main(int argc, const char *argv[])
{
joseph(8,3,4);
return 0;
}