約瑟夫環生死問題,利用循環鏈表作爲存儲結構,使用簡單的c++語言知識便可實現。
由於算法並不複雜,故並未使用多個函數,在一個主函數中實現
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int ElemType;
typedef struct lnode
{
ElemType data;
struct lnode *next;
}node, *linklist;
int main()
{
int n, i = 1, k;
node *p, *q;
linklist head;
cin >> n >> k;
if (n % 2 != 0)
cout << "請輸入偶數,否則無法實現。" << endl;
head = (node*)malloc(sizeof(node));
head->data = 1;
q = head;
p = head;
for (int l = 2; l <= n; l++)
{
p = (linklist)malloc(sizeof(node));
q->next = p;
q = p;
p->data = l;
}
q->next = head;//循環單鏈表創建完成
p = head;
cout << "死亡人員:";
while (i <= n / 2)
{
for (int m = k; m >2; m--)
p = p->next;
q = p->next;
p->next = q->next;
cout << q->data << " ";
free(q);
p = p->next;
i++;
}//死亡人員確認
cout << endl << "倖存人員:";
i = 1;
while (i <= n / 2)
{
p = p->next;
cout << p->data << " ";
i++;
}
cout << endl;
return 0;
}