#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct people)
struct people
{int num;
int sec;
struct people *next;
};
int n;
struct people *creat(void)
{struct people *head,*p1,*p2;
int i;
head=p1=p2=(struct people*)malloc(LEN);
p1->num=1;
scanf("%d",&p1->sec);
for(i=2;i<=n;i++)
{p1=(struct people*)malloc(LEN);
p2->next=p1;
p2=p1;
p1->num=i;
scanf("%d",&p1->sec);
}
p2->next=head;
return(head);
}
del(struct people *head,int x)
{struct people *p1,*p2;
int i,s,j;
s=x;
p1=p2=head;
for(i=1;i<n;i++)p1=p1->next;
for(i=1;i<n;i++)
{for(j=1;j<=s;j++)
{p2=p1;p1=p1->next;}
p2->next=p1->next;
s=p1->sec;
printf("The %dth people be deleted.The secret is %d.\n",p1->num,p1->sec);
free(p1);
p1=p2;
}
printf("The last one is the %dth people.\n",p1->num);
}
main()
{struct people *head;
int x;
printf("Please input there are how many people:");
scanf("%d",&n);
printf("please input their secrets:\n");
head=creat();
printf("Who is the first be deleted:");
scanf("%d",&x);
del(head,x);
}
/**********************************************
********* Josephus problem ************
*********************************************/
#include <malloc.h>
#include <stdio.h>
struct boy /* struct of boy*/
{
int num;
struct boy *next;
};
int main()
{
int i;
int number; /* 小孩的数目 */
int interval; /* 即报数从1- interval */
struct boy *head, *p, *current;
printf("please input the number of boys:");
scanf("%d", &number);
printf("please input the interval:");
scanf("%d", &interval);
if(number < interval || number <= 0 || interval <= 0)
{
printf("input error!!!\n");
return 0;
}
head = (struct boy *) malloc(sizeof(struct boy));
head->num = 1;
head->next = NULL;
current = head;
printf("Boy numbers:%d,", head->num);
for (i = 2; i <= number; i++) /* 建立单向循环链表 */
{
p = (struct boy *) malloc(sizeof(struct boy));
p->num = i;
p->next = NULL;
current->next = p;
current = p;
printf(" %d,", p->num);
}
printf("\n");
current->next = head;
current = head;
printf("Out queue order:");
while (current->next != current) /*loop to find the winner */
{
for (i = 1; i < interval; i++) /* 查找报数为interval的小孩结点 */
{
p = current;
current = current->next;
}
p->next = current->next; /* 删除报数为interval的小孩结点 */
printf(" %d,", current->num);
free(current); /* 释放报数为interval的小孩结点空间 */
current = p->next;
}
printf("\n");
printf("No.%d boy's won!\n", current->num);
return 0;
}