约瑟夫问题
设有N个人坐在圆桌周围,从第S个人开始报数,数到M的人出列,然后再从下一个人开始报数,数到
M的人又出列,如此重复,直到所有人都出列为止。按出列顺序输出每个人的信息。
代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node * next;
int value;
};

void CreateList(struct node * head ,int *p,int length)
{
struct node * loc = (struct node *)malloc(sizeof(struct node));
loc->value = *p;
loc->next = head;
head->next = loc;
head->value = NULL;
for(int i=1;i<length;i++)
{
loc->next = (struct node *)malloc(sizeof(struct node));
loc = loc -> next ;
loc -> value = *(++p);
}
loc->next = head ;
}

int main()
{
int s,m;
scanf("%d",&s);
scanf("%d",&m);
int values[10] = {1,2,3,4,5,6,7,8,9,10};
struct node * head = (struct node *)malloc(sizeof(struct node));
head->value = NULL;
CreateList(head,values,sizeof(values)/4);
struct node * p = head ;
for(int i=0;i<s-1;i++)
{
p = p->next;
if(p==head) p=head->next;
}
for(int i=0;i<sizeof(values)/4;i++)
{
for(int j=0;j<m-1;j++)
{
p = p->next;
if(p==head) p=head->next;
}
struct node * temp = p->next==head?head->next:p->next;
printf("%d,\t",temp->value);
if(p->next==head) head->next = head->next->next;
else p->next = p->next->next;
free(temp);
}
getchar();
getchar();
}
DEV C++ 编译通过。
M的人又出列,如此重复,直到所有人都出列为止。按出列顺序输出每个人的信息。
代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node * next;
int value;
};
void CreateList(struct node * head ,int *p,int length)
{
struct node * loc = (struct node *)malloc(sizeof(struct node));
loc->value = *p;
loc->next = head;
head->next = loc;
head->value = NULL;
for(int i=1;i<length;i++)
{
loc->next = (struct node *)malloc(sizeof(struct node));
loc = loc -> next ;
loc -> value = *(++p);
}
loc->next = head ;
}
int main()
{
int s,m;
scanf("%d",&s);
scanf("%d",&m);
int values[10] = {1,2,3,4,5,6,7,8,9,10};
struct node * head = (struct node *)malloc(sizeof(struct node));
head->value = NULL;
CreateList(head,values,sizeof(values)/4);
struct node * p = head ;
for(int i=0;i<s-1;i++)
{
p = p->next;
if(p==head) p=head->next;
}
for(int i=0;i<sizeof(values)/4;i++)
{
for(int j=0;j<m-1;j++)
{
p = p->next;
if(p==head) p=head->next;
}
struct node * temp = p->next==head?head->next:p->next;
printf("%d,\t",temp->value);
if(p->next==head) head->next = head->next->next;
else p->next = p->next->next;
free(temp);
}
getchar();
getchar();
}
DEV C++ 编译通过。


浙公网安备 33010602011771号