前幾日看到一個關於約瑟夫環的面試題,於是試著動手做了一下,沒有采用.Net類庫的LinkedList類,自己實現了一個循環鏈表結構,然後模擬游戲過程得出結果。
具體代碼如下:
代碼
class Program
{
static void Main(string[] args)
{
const int HUMAN_MAX = 17;
const int HUMAN_INDEX = 3;
const int HUMAN_NUMBER = 0;
LinkTable<Human> list = new LinkTable<Human>();
for (int i = 0; i < HUMAN_MAX; i++)
{
list.Add(new Human(i));
}
Human human = list.First;
int number = HUMAN_NUMBER;
do
{
if (number == HUMAN_INDEX)
{
number = 0;
Console.WriteLine(human.ID);
list.Remove(human);
}
else
{
number++;
human = (Human)human.Next;
}
}
while (human.Next != human);
Console.WriteLine(human.ID);
Console.Read();
}
public class Human : LinkT