原题链接:[编程入门]链表之报数问题
解题思路: 构建循环链表,然后进行报数操作,3的倍数将序号修改为0;直到淘汰人数为总人数减一;
接着遍历链表,打印序号不为0的值.
注意事项: 注意循环链表,首尾相连. 别忘记点赞噢
参考代码:
#include<stdio.h>
#include<stdlib.h>
int num = 0; //定义全局变量,记录淘汰人数
typedef struct node
{
int date;
struct node* next; //定义结构体,储存序号和结构体指针
}Node;
struct list
{
struct node *head; //定义结构体,存放两个指针,方便使用,一个头指针,一个尾指针
struct node *tail;
}List;
void init(struct list List)
{
List.head = NULL; //初始化结构体指针
List.tail = NULL;
}
void creatNode(struct list *List, int data)
{
Node *node = (Node *)malloc(sizeof(Node));
node->date = data;
node->next = NULL;
if (!List->head) //创建结点
{
List->head = List->tail = node;
}
else
{
List->tail->next = node;
List->tail = node;
}
}
void play(struct list *List,int n)
{
int m = 1;
Node *p = List->head;
while (num < n - 1)
{
if (p->date)
{ //进行操作,报到3的倍数,序号修改为0
if (m % 3 == 0)
{
p->date = 0;
num++;
}
m++;
}
p = p->next; //移动指针,指向下一个结点
}
}
void search(struct list *List)
{
Node *p = List->head;
while (1)
{ //遍历整个循环链表,出现序号不为0 ,直接打印序号
if (p->date)
{
printf("%d\n", p->date);
break;
}
p = p->next;
}
}
int main()
{
int n, i;
scanf("%d", &n);
init(List);
for (i = 1; i <= n; i++)
{
creatNode(&List, i);
}
List.tail->next = List.head; //尾指针指向头指针,成为循环链表
play(&List, n);
search(&List);
return 0;
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复