1.知识点:循环链表
2.题意:已知排长是1号,从1号开始数,数到5的那名战士去执行任务,那么排长是第几个去执行任务的
3.注意事项:注意循环链表删除节点的前后节点的指针域的指向变化
代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int Data;
struct node *next;
}*head, *tail;
void Build(int n);//顺序建立循环链表
void Search_ans();//在循环链表中查找最优解
int main()
{
int n;
while(scanf("%d", &n) && n != 0)
{
if(n == 1)
printf("%d\n", n);
else
{
head = (struct node *)malloc(sizeof(struct node));
head->Data = 1;
head->next = NULL;
tail = head;
Build(n);//顺序建立循环链表
Search_ans();//在循环链表中查找最优解
}
}
return 0;
}
void Build(int n)//顺序建立循环链表
{
struct node *p;
for(int i = 2; i < n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->Data = i;
p->next = tail->next;
tail->next = p;
tail = p;
}
p = (struct node *)malloc(sizeof(struct node));
p->Data = n;
tail->next = p;
p->next = head;
}
void Search_ans()//在循环链表中查找最优解
{
int cnt = 0;//判断当前结点是否符合执行任务的题意
int flag = 1;//记录之前有几名士兵执行任务
struct node *q, *p;
q = tail->next;
p = head;
while(1)//通过while循环中的符合题意的语句中的break语句来结束while循环
{
cnt++;
if(cnt % 5 == 0)
{
if(p->Data == 1)
{
printf("%d\n", flag);
break;
}
else
{
q->next = p->next;
free(p);
p = q->next;
flag++;
}
}
else
{
q = p;
p = p->next;
}
}
}
1324

被折叠的 条评论
为什么被折叠?



