单链表实现约瑟夫,不是很好做,我试过很多方法单链表实现约瑟夫
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 关于#hadoop#的问题
- ¥15 (标签-Python|关键词-socket)
- ¥15 keil里为什么main.c定义的函数在it.c调用不了
- ¥50 切换TabTip键盘的输入法
- ¥15 可否在不同线程中调用封装数据库操作的类
- ¥15 微带串馈天线阵列每个阵元宽度计算
- ¥15 keil的map文件中Image component sizes各项意思
- ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
- ¥15 划分vlan后,链路不通了?
- ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据