題目:17個人圍成一圈,從第一個人開始報數,報到3的退出,一直到剩下最後一個人,用面向對象的思想去做這道題。
我自己也來做一做這道題。
public class person
{
public person Prev { get; set; }
public person Next { get; set; }
public int Val { get; set; }
public person() { }
public person(person pre,person next,int val) {
Prev = pre;
Next = next;
Val = val;
}
}
class Program
{
static void Main(string[] args)
{
var rootperson = new person();
rootperson.Val = 1;
//初始化數據
person temp = rootperson;
for (int i = 2; i <= 17; i++)
{
var p = new person(temp, null, i);
temp.Next = p;
temp = p;
}
temp.Next = rootperson;
rootperson.Prev = temp;//最後一個與第一個連接上
//輸出
int j = 1;
person start = rootperson;
while (start.Next != null)
{
if (j % 3 == 0) remove(start);
start = start.Next;
j++;
}
Console.ReadLine();
}
public static void remove(person p)//輸出並退出鏈環
{
Console.WriteLine(p.Val);
if (p.Prev != p.Next)
{
p.Prev.Next = p.Next;
p.Next.Prev = p.Prev;
}
else//只剩下兩人的時候
{
p.Prev.Next = null;
p.Prev.Prev = null;
}
}
}
輸出結果:

大家也不妨來練一練,提提你的意見。