假如有M个人想用以下方法来选出一个领袖:M个人围成一个圈,从某个人开始按顺序数数,每次数到N那个人出局,最后仅存的那个人就是领袖。
用循环链表来表示这M个人,不断循环链表,每当数到N,那个结点去掉,直到只剩一个结点为止。
class Node
{
public int index;//表示第几个人
public Node next;
public Node(int x, Node t)
{
index= x;
next = t;
}
}
class Program
{
//用尾插法(新插入的结点总在最后)建一个循环链表
static Node CreateLister(int m)
{
Node head,s,r;
//第一个结点
head = new Node(1, null);
head.next = head;
//尾指针
r = head;
for (int i = 2; i <= m; i++)
{
s = new Node(i, head);//新结点,指向头指针
r.next = s;//新结点插入表尾
r = s;//尾指针指向新的表尾
}
r.next = head;//表尾的下一个接着表头,形成循环
return r;//返回尾指针
}
static void Main(string[] args)
{
const int M = 9;
const int N = 5;
Node x = CreateLister(M);
while (x != x.next)
{
//跳到出局的人的前一个人
for (int i = 1; i < N; i++)
{
x = x.next;
}
Console.Write(x.next.item.ToString() + ",");
x.next = x.next.next;//第N个人出局
}
Console.Write(x.item.ToString());
Console.Read();
}
}