当前位置: 首页 > news >正文

环形链表的约瑟夫问题

一:题目

二:思路

前提:该题已经声明了结构体,只是看不见,声明如下:

因为是从0开始实现:

1:创建一个n个节点的循环链表,其值为1~n(假设n = 5)

如图:

代码如下: 
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));if (newnode == NULL){perror("malloc failed");return NULL;}newnode->val = i;newnode->next = NULL;return newnode;}
struct ListNode* CreatList(int n)
{int i = 1;struct ListNode* head = NULL;struct ListNode* tail = NULL;while (i <= n){struct ListNode* newnode = BuyNode(i++);if (tail == NULL){head = tail = newnode;}else{tail->next = newnode;tail = tail->next;}}tail->next = head;return head;
}
代码解释:

a:用了一个BuyNode函数,来创造节点

b:循环中BuyNode的参数是i++,得到的节点的值从1到n(因为i<=n)

第一次得到节点:

非第一次得到节点:tail进行移动就行。

c:最后得到的五个节点是一个单链表,需要tail的next指向head才能形成循环链表

 

2:约瑟夫函数的实现

假设m = 2 ,即报数到2的人离开

流程如下:

 

代码如下:
int ysf(int n, int m) {struct ListNode* head = CreatList(n);struct ListNode* cur = head;struct ListNode* prev = NULL;int i = 1;while (cur != cur->next){if (i == m){prev->next = cur->next;cur = prev->next;i = 1;}else{prev = cur;cur = cur->next;i++;}}return cur->val;}
代码解释:

1:cur的next是自己,就代表只有一个节点了,不再进入循环

2:i代表报数的数字,i没到2,则prev和cur双双向后移动

3:i到2,则进行cur节点的移除,然后根据题目要求,i=1,重新开始报数

4:最后只有一个节点,返回其值。 

三:总代码

struct ListNode* BuyNode(int i)
{struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));if (newnode == NULL){perror("malloc failed");return NULL;}newnode->val = i;newnode->next = NULL;return newnode;}
struct ListNode* CreatList(int n)
{int i = 1;struct ListNode* head = NULL;struct ListNode* tail = NULL;while (i <= n){struct ListNode* newnode = BuyNode(i++);if (tail == NULL){head = tail = newnode;}else{tail->next = newnode;tail = tail->next;}}tail->next = head;return head;
}int ysf(int n, int m) {struct ListNode* head = CreatList(n);struct ListNode* cur = head;struct ListNode* prev = NULL;int i = 1;while (cur != cur->next){if (i == m){prev->next = cur->next;cur = prev->next;i = 1;}else{prev = cur;cur = cur->next;i++;}}return cur->val;}

 

 

 

 

 


http://www.mrgr.cn/news/37676.html

相关文章:

  • 华为 HCIP-Datacom H12-821 题库 (27)
  • 【C++】函数模板,类模板,全特化,偏特化详解
  • FPGA学习(3)-38译码器实现
  • WEB3.0是什么?
  • [element-ui]记录对el-table表头样式的一些处理
  • 【SQLite】sqlite | insert插入存在即更新
  • 【C#生态园】解锁C#开发新姿势:探秘六大Word处理库功能对比
  • 初学者教程:如何使用谷歌云API
  • Kubernetes深入详解(一)
  • 【linux】linux中如何通过Logstash处理、结合logrotate分割日志
  • 在深度学习训练过程中模型为什么会学习到捷径
  • 如何向远程仓库上传项目
  • Python教程:类调用实例方法
  • 大屏走马灯与echarts图表柱状图饼图开发小结
  • leetcode力扣刷题系列——每种字符至少取 K 个
  • 面试中如何做自我介绍
  • 完美解决Ubuntu下vi编辑器方向键变字母的问题
  • 聊聊不同的理由展现不同的人格
  • MySQL—索引机制详解
  • HAL+M4学习记录_2