当前位置:   article > 正文

数据结构:单链表问题(约瑟夫环)_数据结构单链表过程的问题

数据结构单链表过程的问题

题目有:

随机给定一个数作为起始循环次数n,循环n次后当前节点的人淘汰,然后以它的号码为下一次的循环性次数,循环往复,最终留下一个人为获胜者,求是第几号的人。

  1. node* create() { //首先暴力创建一个单项循环链表
  2. node* head = new node(1, 15);
  3. head->next = new node(2, 21);
  4. head->next->next = new node(3, 14);
  5. head->next->next->next = new node(4, 1);
  6. head->next->next->next->next = new node(5, 12);
  7. head->next->next->next->next->next = new node(6, 8);
  8. head->next->next->next->next->next->next = head;
  9. return head;
  10. }

 创建结构体由三部分组成

  1. struct node { //结构体为如下 val是编号 ,secret是那个会被当做是循环次数的值
  2. int val;
  3. int secret;
  4. node* next;
  5. node(int n, int m) :secret(m), val(n), next(nullptr) {}
  6. };

开始进入方法体

  1. int* yuesefu(node* head) {
  2. const int count = 2;//以常数模拟, 初次给定的移动的次数
  3. int cur = count; //用来记录循环次数
  4. int* arr = new int[6]; //在堆中创建临时数组,c语言没有垃圾回收需要释放
  5. int i = 0; //i是arr用来记录被淘汰的人的编号的数组的下标
  6. node* temp = nullptr;
  7. //终止条件是当head的下一个是自己时,说明当前链表是一个只剩一个节点的单链表
  8. while (head->next != head) {
  9. while (cur != 0) {//循环cur次
  10. if (cur == 1)
  11. temp = head;//用temp指针记录到需要被删除的节点的前一个节点
  12. head = head->next;
  13. cur--;
  14. }
  15. cur = head->secret; //取出secret作为新一次循环的值
  16. arr[i++] = head->val; //把淘汰的值放到数组中
  17. cout << "被淘汰:" << head->val << endl;
  18. temp->next = temp->next->next; //关键点移除head指向的链表
  19. temp = temp->next;
  20. head = temp;
  21. }
  22. arr[i] = head->val;//获胜者记录在数组结尾
  23. return arr;
  24. }

约瑟夫环已问题解决

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/680884
推荐阅读
相关标签
  

闽ICP备14008679号