有N个小孩围成一圈,给他们从1开始依次编号,现指定从第W个开始报数,报到第S个时,该小孩出列,然后从下一个小孩开始报数,仍是报到S个出列,如此重复下去,直到所有的小孩都出列(总人数不足S个时将循环报数),求小孩出列的顺序。
解法一双向循环链表设计创立 删除
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
struct List//双向链表结构体
{
char name[20];
struct List *front; //前指针
struct List *rear; //后指针
};
List* create(int n)
{
List *node,*head; //定义头结点和尾结点
head = node = new List;
for(int i = 2;i <=n ;i++)
{
node->rear = new List; //初始化后指针
node->rear->front = node; //双向指向
node = node->rear;
}
node->rear = head;
head->front = node;
return head;
}
List* move(List* p,int step) //链表计数移动
{
for(int i = 1;i < step ; i++)
{
p = p->rear;
}
return p;
}
List* remove(List* p) //删除结点操作
{
p->front->rear = p->rear;
p->rear->front = p->front;
p = p->rear; //删除结点三步走
return p;
}
int main()
{
int n,w,s;
scanf("%d",&n);
List *node,*head;
head = node =create(n);
for(int i =1;i <= n;i++)
{
scanf("%s",node->name);
node = node->rear;
}
scanf("%d%d",&w,&s);
node = move(head,w);
while(node->rear != node) //循环遍历终止条件
{
node = move(node,s);
printf("%s\n",node->name);
node = remove(node);
}
printf("%s\n",node->name); //最后一个结点要输出
}
方法二 : 单向循环链表
//方法二单向链表
#include<stdio.h>
#include<iostream>
using namespace std;
struct ch
{
char name[100];
struct ch *next;
};
int main()
{
int N=0,i=0,w=0,s=0,j=0;
struct ch *p = NULL,*head = NULL,*NEW = NULL,*q = NULL;
scanf("%d",&N);
for(i=0;i<N;i++)
{
NEW = new ch();
scanf("%s",NEW->name);
if(p==NULL)
{
head = NEW;
p = NEW;
}
else
{
p->next = NEW;
p = NEW;
}
}
p->next = head;
scanf("%d%d",&w,&s);
p = head;
for(i=1;i<w;i++)
{
p = p->next;
}
q = p;
for(i=0;i<N;i++)
{
for(j=1;j<s;j++) //循环一次出去一个人少一个人
{
q = p;
p = p->next;
}
printf("%s\n",p->name);
q->next = p->next;
p = q->next;
}
}
重要的是建立链表的思想
然后在具体构建链表
版权声明:本文为博主原创文章,未经博主允许不得转载。