单链表实现约瑟夫,不是很好做,我试过很多方法单链表实现约瑟夫
2条回答 默认 最新
- qzjhjxj 2022-06-04 16:13关注
供参考:
#include <stdio.h> #include <stdlib.h> typedef int Elemtype; typedef struct LNode{ Elemtype data; struct LNode *next; }LNode,*Linklist; void Createlist(Linklist* L,int n) { Linklist p,tail; (*L) = (Linklist)malloc(sizeof(LNode)); (*L)->next = (*L);//先使其循环 p = (*L); p->data = 1;//创建首节点先给首节点赋值 tail = (*L); for(int i = 2;i <= n;i++) { p = (Linklist)malloc(sizeof(LNode)); p->data = i; p->next = (*L); tail->next = p; tail = p; } } void Listtrave(Linklist L,int n)//遍历函数 { Linklist p; p = L; for(int i = 1;i <= n;i++) { printf("%4d",p->data); p = p->next; } printf("\n"); } Linklist Solution(Linklist L,int n,int b) { Linklist p = L,s = L; int count = 1; while(n > 2) { if(count != b)//不等于 b 时的移位 { count++; p = p->next; } else { Linklist q = p;//用q保存p所指的位置,方便进行节点的删除 count = 1;//将count重置为1 printf(n == 3 ? "%4d\n" : "%4d", p->data);//打印出局的值 while(s->next != p) s = s->next;//将s移位到p的前驱节点处 p = p->next;//使p指向自己的下一个节点 s->next = p;//进行删除 free(q); n--; //人数减一 } } if(s->data > p->data) return p; else return s; } int main() { Linklist L; int n , b; scanf("%d%d",&n , &b); Createlist(&L,n); printf("创建的约瑟夫环为:\n"); Listtrave(L,n); printf("依次出局的结果为:\n"); L = Solution(L,n,b); Listtrave(L,2); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 CATIA有些零件打开直接单机确定终止
- ¥15 请问有会的吗,用MATLAB做
- ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
- ¥15 ARIMA模型时间序列预测用pathon解决
- ¥15 孟德尔随机化怎样画共定位分析图
- ¥18 模拟电路问题解答有偿速度
- ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
- ¥15 误删注册表文件致win10无法开启
- ¥15 请问在阿里云服务器中怎么利用数据库制作网站
- ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址