一共有n个人,围成一圈,从1开始报数,数到m的人出局,然后重新开始报数。算出出局的人的顺序。\n\n要求:用顺序和链式存储两种方法完成\n\n \n\n程序清单(黑色五号字体):\n\n#include <stdio
时间: 2023-05-02 22:02:15 浏览: 282
这道题要求写一个算法,从1开始报数,数到m的人出列,然后从下一个人重新开始报数,直到所有人都出列为止。同时要求用顺序和链式存储两种方法完成。
程序清单(黑色五号字体):
#include <stdio.h>
#include <stdlib.h>
/*使用数组存储*/
int Queue[1000];
int head, tail;
void link()
{
int n, m, i;
int count = 0;
head = 1;
tail = 1;
printf("Please input n and m:");
scanf("%d%d", &n, &m);
if (n < 1 || m == 0 || n > 1000)
{
printf("Input is invalid.\n");
return;
}
for (i = 1; i <= n; i++)
{
Queue[i] = i;
tail++;
}
tail--;
while (head < tail)
{
count++;
if (count == m)
{
printf("%d ", Queue[head]);
head++;
count = 0;
}
else
{
Queue[tail] = Queue[head];
head++;
tail++;
}
}
printf("%d\n", Queue[head]);
}
/*使用链表存储*/
typedef struct Node
{
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createLinkedList()
{
LinkedList L;
L = (LinkedList)malloc(sizeof(Node));
L->next = NULL;
return L;
}
void linkList()
{
int n, m, i;
int count = 0;
LinkedList L, p, q;
L = createLinkedList();
printf("Please input n and m:");
scanf("%d%d", &n, &m);
if (n < 1 || m == 0 || n > 100000)
{
printf("Input is invalid.\n");
return;
}
p = L;
for (i = 1; i <= n; i++)
{
q = (LinkedList)malloc(sizeof(Node));
q->data = i;
p->next = q;
p = q;
}
p->next = L->next;/*形成循环链表*/
p = L->next;
while (p != p->next)
{
count++;
if (count == m)
{
printf("%d ", p->data);
q = p;
p = p->next;
q->next = p->next;
free(p);
p = q->next;
count = 0;
}
else
{
p = p->next;
}
}
printf("%d\n", p->data);
}
int main()
{
link();
linkList();
return 0;
}
阅读全文