• 循环链表解决约瑟夫环问题


     1 /**
     2  * 循环链表求解约瑟夫环问题
     3  **/
     4 #include <iostream>
     5 #include <cstdlib>
     6 using namespace std;
     7 
     8 /**
     9  * 数据结构
    10  **/
    11 typedef struct DanamicList {
    12     int id;
    13     struct DanamicList* next;
    14 } List;
    15 
    16 /**
    17  * 创建循环链表
    18  **/
    19 List* InitList(int numCount) {
    20     if(numCount <= 0) {
    21         cout << "Value is invalid!!!
    ";
    22         exit(-1);
    23     }
    24     List *head = head = new List;
    25     if(!head) {
    26         cout << "Alloc memory failed!!!
    ";
    27         exit(-1);
    28     }
    29 
    30     head->id = 1;
    31     List *pre = head;
    32     for(int index = 1; index < numCount; ++index) {
    33         List *temp = new List;
    34         if(!temp) {
    35             cout << "Alloc memory failed!!!
    ";
    36             exit(-1);
    37         }
    38         temp->id = index + 1;
    39         temp->next = NULL;
    40         pre->next = temp;
    41         pre = temp;
    42     }
    43     pre->next = head;
    44 
    45     return head;
    46 }
    47 
    48 /**
    49  * 求解约瑟夫环问题
    50  **/
    51 void josephus(List* head, int number) {
    52     int count = 0, flag = 0;
    53     List *pre = head, *del = NULL;
    54 
    55     while(pre->next != head)
    56         pre = pre->next;
    57     do {
    58         ++count;
    59         if(number != count)
    60             pre = pre->next;
    61         else {
    62             count = 0;
    63             del = pre->next;
    64             cout << del->id << "	";
    65             pre->next = pre->next->next;
    66             if (pre != pre->next)
    67                 delete del;
    68         }
    69         if(pre == pre->next)
    70             ++flag;
    71     } while(flag - (number + 1));             // 数学关系
    72     delete pre;
    73 }
    74 
    75 /**
    76  * 主函数
    77  **/
    78 int main(void) {
    79     List *head = NULL;
    80     int totalPeople = 0, outNumber = 0;
    81     cout << "请输入总数和出队密码:";
    82     cin >> totalPeople;
    83     cin >> outNumber;
    84 
    85     head = InitList(totalPeople);             // 创建循环链表
    86     josephus(head, outNumber);                // 求解约瑟夫环
    87 
    88     return 0;
    89 }
  • 相关阅读:
    MySQL的数据库,数据表,数据的操作
    数组函数
    字符串函数,时间函数,数学函数,数组
    PHP函数
    php类型的相关函数,运算符,条件判断,循环
    PHP数据类型
    vector中erase用法注意事项
    C++11 右值引用&&
    vector中find和find_if的用法 以后再遍历剁手!
    在cocos2d中添加自己的shader教程
  • 原文地址:https://www.cnblogs.com/gotodsp/p/3843587.html
Copyright © 2020-2023  润新知