原题链接:[编程入门]报数问题
解题思路:
注意事项:
参考代码:
#include<stdio.h>
#include<stdlib.h>
struct student
{
int num;
struct student *pnext;
};
int count=1; //记录节点数
struct student *creat(struct student *phead,int n) //创建循环链表
{
struct student *pnew=NULL,*pend=NULL;
pnew=pend=(struct student*)malloc(sizeof(struct student));
pnew->num=1;
while(n!=count)
{
if(count==1)
{
pnew->pnext=phead;
phead=pnew;
}
else
{
pnew->pnext=pend->pnext;
pend->pnext=pnew;
pend=pnew;
}
count++;
pnew=(struct student*)malloc(sizeof(struct student));
pnew->num=count;
}
pend->pnext=phead; //将最后一个节点与头结点相连形成约瑟夫环
free(pnew);
return phead;
}
int f(struct student *phead)
{
struct student *ptemp=phead,*pre=phead; //将两个指针指向第一个节点
pre=pre->pnext; //pre为删除的前一个节点
ptemp=pre->pnext; //要删除的节点
while(pre!=ptemp) //当只有一个节点时循环结束
{
pre->pnext=ptemp->pnext; //让前一个节点与后一个节点相连
free(ptemp); //释放删除节点
pre=pre->pnext->pnext->pnext; //让前一个节点连续前进三位
ptemp=pre->pnext; //pre为要删除节点的前一位,前进三位,下一位是下一个要删除的节点
}
return pre->num; //返回数据
}
int main()
{
int n,a;
struct student *phead=NULL;
if(scanf("%d",&n));
phead=creat(phead,n);
a=f(phead);
printf("%d",a);
return 0;
}0.0分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复