第18讲课后题参考答案
按自己的思路写的,运行结果和小甲鱼的一样。供参考:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int id;
int data;
struct node *next;
}node;
node *create(int n)
{
node *head = (node *)malloc(sizeof(struct node)), *p,*temp;
p = head;
int i;
int password;
if(n != 0)
{
for(i = 1; i <= n; i++)
{
temp = (node *)malloc(sizeof(struct node));
temp->id = i;
printf("请为第%d个人输入密码:", i);
scanf("%d", &password);
temp->data = password;
p->next = temp;
p = temp;
}
temp->next = head->next;
}
free(head);
return p->next;
}
int main()
{
node *p,*temp;
int m, n, i, j = 1;
printf("请输入人数:");
scanf("%d", &n);
p = create(n);
printf("请输入报数上限:");
scanf("%d", &m);
//m %= n;
while(p != p->next)
{
if(m == 1)
{
temp = p->next;
do
{
temp = temp->next;
}
while(p != temp->next);
p = temp;
}
else
{
for(i = 1; i < m -1; i++)
{
p = p->next;
}
}
printf("第 %d个出列的人是:%d, 密码是:%d\n", j, p->next->id, p->next->data);
temp = p->next;
p->next = temp->next;
m = temp->data;
free(temp);
p = p->next;
j++;
}
printf("第 %d个出列的人是:%d, 密码是:%d\n", j, p->next->id, p->data);
return 0;
}最后欢迎讨论!
页:
[1]