晚自习两个钟头,就这个题目,硬是没有做出来。。
有N个人围成一圈,顺序排号,从第一个人开始报数( 从1到3 ),凡报到3的人退出圈子,问最后留下的是原来第几号的那位?
程序代码:/*
程序采用循环链表的算法实现
m个人围成圈,报到n的人退出,求最后一位的原始编号
*/
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
long int m,n;
struct node *h;
struct node /*链表结点结构*/
{
struct node *next;
int data;
};
struct node * create(struct node *h) /*创建单向循环链表*/
{
struct node *p,*q; int i;
h=p=q=(struct node *)malloc(sizeof(struct node));
p->next=NULL; p->data=1;
for(i=2;i<=m;i++)
{
p=(struct node *)malloc(sizeof(struct node));
q->next=p; p->data=i; p->next=NULL;
q=p;
}
p->next=h;
return h;
}
int fun(struct node *h) /*操作链表*/
{
struct node *p=h,*q; int i;
if(n>1)
{
while(p->next!=p)
{
i=1;
while(i<n-1) {p=p->next; i++;}
q=p->next;
p->next=q->next;q->next=NULL;
free(q);
p=p->next;
}
}
else if(n==1)
{
p->data=m;
}
return p->data;
}
int main()
{
struct node *h;
printf("请输入总人数m:");
scanf("%d",&m);
printf("再输入退出者号n:");
scanf("%d",&n);
h=create(h);
printf("最后一位号码是:");
printf("%d\n",fun(h));
return 0;
}
程序代码:#include<stdio.h>
#define N 10
main()
{
int n,m,i,k=0;
int a[N];
n=N;
for(i=0;i<N;i++)
a[i]=i+1;
printf("input the number:");
scanf("%d",&m); /*令m=3就好*/
while(n>1)
{
if(i==N)
i=0;
if(a[i])
k++;
if(k==m)
{
printf("a[%d]=%-5d",i,a[i]); /*被删除的数*/
a[i]=0;
k=0;
n--;
}
i++;
}
i=-1;
while(!a[++i]); /*剩下的数*/
printf("\na[%d]=%d\n",i,a[i]);
return 0;
}
建议你换一下头像,看着不舒服。
程序代码:/* Note:Your choice is C IDE */
#include "stdio.h"
#include "malloc.h"
/*#define NULL 0*/
#define LEN sizeof(struct person)
struct person
{
int num;
struct person *next;
};
int n;
struct person *create(void)
{ struct person *head,*p1,*p2;
n=0;
p1=p2=(struct person*)malloc(LEN);
head=p1;
while(n!=13)
{
n=n+1;
p2->num=n;
if(n!=13)
{
p1=(struct person*)malloc(LEN);
p2->next=p1;
p2=p1;
}
}
p2->next=NULL;
return(head);
}
void print(struct person *head)
{
struct person *p;
p=head;
if(head!=NULL)
{do
{
printf("%d ",p->num);
p=p->next;
}while(p!=NULL);
printf("\n");}
else
printf("error");
}
struct person *select(struct person *head)
{ struct person *heads,*p,*q;
static i=1;
heads=head;
q=p=heads;
while(p!=NULL)
{
if(i%3!=0)
{
q=p;
p=p->next;
i=i+1;
}
else
{ if(p!=heads)
q->next=p->next;
else {
heads=p->next;
q=heads;
}
p=p->next;
i=i+1;
n=n-1;}
}
if(n>1){heads=select(heads);}
return (heads);
}
void main()
{
struct person *head;
head=create();
print(head);
head=select(head);
print(head);
}我也是新手,多思考!!出现了问题自己查找错误 多动手调试就行了!!!