地雷的拆解:简单基础的C语言编程问题(虽然很简单但是对于我好难555)

来源:百度文库 编辑:神马品牌网 时间:2024/05/02 06:44:32
N(N<100)个人围成一圈,按顺序排号。从第一个人开始报数(从1到5报数),凡报到5的人退出圈子,问最后留下的是最初的第几号。用两种方法实现,一种是仅用数组实现,另一种用指向数组的指针实现。
请问有人可以提供思路吗???

用数组的
#include <stdio.h>
#define N 100
#define S 1
#define M 5
int p[100], n, s, m;

void Josegh(void)
{
int i, tmp;
for (i=0; i<n; i++)
p[i] = i+1;
s = s-1;
while (n > 1)
{
s = (s+m-1)%n;
tmp = p[s];
for (i=s+1; i<n; i++)
p[i-1] = p[i];
p[n-1] = tmp;
n--;
}
}
void main()
{
m = M;
n = N;
s = S;
Josegh();
}
数组指针:
#include <stdio.h>
main()
{
int i,k,m,n,num[50],*p:
printf("input number of person:");
scanf("%d",&n);
p=num;
for(i=0;i<n;i++)
*(p+i)=i+1;
i=0;
k=0;
m=0;
while(m<n-1)
{
if(*(p+i)!=0)
k++;
if(k==5)
{
*(p+i)=0;
k=0;
m++;
}
i++;
if(i==n)
i=0;
}
while(*p==n)
p++;
printf("the last one is %d\n",*p);
}

都盲打的,运行很可能有错
自己调试一下就可以
大问题应该没有
楼上的用链表的
楼主已经说要求用数组和指针了。。。
用数组的算法比链表的巧妙得多

#include <stdlib.h>
#include <stdio.h>
typedef struct node
{
int data;
struct node *next;
}LNode;

main()
{
LNode* Create(int,int);
LNode* GetNode(LNode *);
int Print(LNode *,int);
LNode *p;
int n=30,k=1,m=9;
p=Create(n,k);
Print(p,m);
return 0;
}

LNode* Create(int n,int k)
{
int start=k-1;
LNode *s,*p,*L=0,*t;
if (start==0) start=n;
while (n!=0)
{
s=(LNode *)malloc(sizeof(LNode));
if (L==0) p=s;
if (n==start) t=s;
s->data=n;
s->next=L;
L=s;
n--;
}
p->next=L;
return t;
}

LNode* GetNode(LNode *p)
{
LNode *q;
for (q=p;q->next!=p;q=q->next);
q->next=p->next;
free (p);
return (q);
}

Print(LNode *p,int m)
{
int i;
printf ("out number:\n");
while (p->next!=p)
{
for (i=1;i<=m;i++)
p=p->next;
printf ("%d ",p->data);
p=GetNode(p);
}
printf("%d\n",p->data);
return 0;
}

程序太多了
有点难打

楼上的第一个程序好像便一通不过的。我用的是cpp。。不知道你检查一下没有,第50行好像有错误的。