python约瑟夫环单向循环链表_约瑟夫环的单向循环链表的实现代码
/*************************************************************************
> File Name: JosephCirle.c
> Author: Wenfei6316
> Mail: wenfei6316@163.com
> Created Time: 2018年06月18日 星期一 09時42分28秒
************************************************************************/
/*約瑟夫環說明:N(N>1) 個人組成一圈,從第 num 個人開始報數(從 1 開始報數)
*當誰報到數字 count 時將執行槍決,然后繼續從后面一位開始接著循環,
*直到最后只剩下一個人,利用單向循環鏈表模擬出每次被殺的人以及最后存活的人*/
#include
#include
#include
typedef enum{false, true}bool;
typedef int data_t;
typedef struct Node
{
data_t data;
struct Node *next;
}JosephNode, *JosephLise;
JosephLise CreateList(int num);
void PrintList(JosephLise cyclelist);
void KillGame(JosephLise cyclelist, int num, int killer);
int main(int argc, const char *argv[])
{
int count = 10;
int num = 8;
int killer = 15;
JosephLise josephcirle;
josephcirle = CreateList(count);
PrintList(josephcirle);
printf("%d is beginning!\n", num);
printf("Calling %d will be killed!\n", killer);
KillGame(josephcirle, num, killer);
return 0;
}
JosephLise CreateList(int num)
{
int i;
JosephLise p, q, s;
if (num < 2)
{
printf("It is insignificance!\n");
exit(EXIT_FAILURE);
}
p = (JosephLise)malloc(sizeof(JosephNode));
if (p == NULL)
{
perror("Create JosephCirle failed!\n");
exit(EXIT_FAILURE);
}
p->data = 1;
p->next = NULL;
q = p;
for (i=2; i<=num; i++)
{
s = (JosephLise)malloc(sizeof(JosephNode));
if (s == NULL)
{
perror("Create JosephCirle failed!\n");
exit(EXIT_FAILURE);
}
s->data = i;
q->next = s;
q = s;
}
q->next = p;
return p;
}
void PrintList(JosephLise cyclelist)
{
bool count = false;
JosephLise p, q;
if (cyclelist == NULL)
{
printf("cyclelist is NULL!\n");
return ;
}
p = cyclelist;
while (!count)
{
printf("%2d ", p->data);
if ((p=p->next) == cyclelist)
count = true;
}
printf("\n");
}
void KillGame(JosephLise cyclelist, int num, int killer)
{
int i;
JosephLise p, q;
if (cyclelist == NULL)
{
printf("Joseph Cirle is error!\n");
return ;
}
if (num<2 || killer<2)
{
printf("It is insignificance!\n");
return ;
}
p = cyclelist;
for (i=1; i
p = p->next;
while (p->next != p)
{
for (i=1; i
p = p->next;
q = p->next;
printf("%d is killed!\n", q->data);
p->next = q->next;
free(q);
q = NULL;
}
printf("Congratulations, you are free, No%d!\n", p->data);
free(p);
return ;
}
總結
以上是生活随笔為你收集整理的python约瑟夫环单向循环链表_约瑟夫环的单向循环链表的实现代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: texlive写论文源代码_Texliv
- 下一篇: 蒙昧的意思_蒙昧的意思