问题描述:设编号为1,2,3,……,n的n(n>0)个人按顺时针方向围坐一圈,m为任意一个正整数。从第一个人开始顺时针方向自1起顺序报数,报到m时停止并且报m的人出列,再从他的下一个人开始重新从1报数,报到m时停止并且报m的人出列。如此下去,直到所有人全部出列为止。要求设计一个程序模拟此过程,对任意给定的m和n,求出出列编号序列。
要求使用顺序表实现
#include<iostream>
#include<malloc.h>
using namespace std;
struct node {
int data;
struct node* next;
};
void solution(int n, int p)
{
//建立循环单链表
node* L = (node*)malloc(sizeof(struct node));
L->data = 1;
L->next = NULL;
node* temp = NULL;//临时指针
node* lastp = L;//指向尾结点的指针
for (int i = 2; i <= n; i++)
{
temp = (node*)malloc(sizeof(struct node));
temp->data = i;
temp->next = NULL;
lastp->next = temp;//插入尾部
lastp = temp;
}
//将尾结点的指针域指向头指针,实现循环单链表
lastp->next = L;
//*************************
node* step = L;//指标指针
node* pr = NULL;//指向删除结点的前结点
//当我的指针指向的结点所在的指针域的值为自己时就结束循环。
while (step->next != step) {
for (int i = 2; i <= p; i++)
{
pr = step;
step = step->next;//比如1 2 3 4.此时step原指向3,pr也指向它。但是step指向了4,因此pr也就指向了目标结点的前一个结点。
}
cout << step->data << " " ;
pr->next = step->next;
step = step->next;
}
cout << step->data;
}
int main()
{
int N, p;
cin >> N >> p;
solution(N, p);
return 0;
}
程序设计思路
测试结果: