使用C#循环链表解决约瑟夫环的问题
前几日看到一个关于约瑟夫环的面试题,于是试着动手做了一下,没有采用.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 : LinkTableNode {
public Human(int id){
this.ID = id;
}
public int ID{get;set;}
}
/// <summary>
/// 圆环链表
/// </summary>
/// <typeparam name="T"></typeparam>
public class LinkTable<T> where T : LinkTableNode
{
public List<T> list = new List<T>();
public T First
{
get
{
return list.Count > 0 ? list[0] : default(T);
}
}
public void Add(T t)
{
t.Previous = list.Count == 0 ? t : list[list.Count - 1];
t.Next = list.Count == 0 ? t : list[0];
if (list.Count > 0)
{
list[0].Previous = t;
t.Previous.Next = t;
}
list.Add(t);
}
public void Remove(T t)
{
int i = list.IndexOf(t);
if(list.Count == 1)
{
list.Remove(t);
}
else
{
t.Previous.Next = t.Next;
t.Next.Previous = t.Previous;
}
}
}
/// <summary>
/// 链表节点
/// </summary>
public class LinkTableNode
{
/// <summary>
/// 下一个节点
/// </summary>
public LinkTableNode Next
{
get;
set;
}
/// <summary>
/// 上一个节点
/// </summary>
public LinkTableNode Previous
{
get;
set;
}
}
}
{
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 : LinkTableNode {
public Human(int id){
this.ID = id;
}
public int ID{get;set;}
}
/// <summary>
/// 圆环链表
/// </summary>
/// <typeparam name="T"></typeparam>
public class LinkTable<T> where T : LinkTableNode
{
public List<T> list = new List<T>();
public T First
{
get
{
return list.Count > 0 ? list[0] : default(T);
}
}
public void Add(T t)
{
t.Previous = list.Count == 0 ? t : list[list.Count - 1];
t.Next = list.Count == 0 ? t : list[0];
if (list.Count > 0)
{
list[0].Previous = t;
t.Previous.Next = t;
}
list.Add(t);
}
public void Remove(T t)
{
int i = list.IndexOf(t);
if(list.Count == 1)
{
list.Remove(t);
}
else
{
t.Previous.Next = t.Next;
t.Next.Previous = t.Previous;
}
}
}
/// <summary>
/// 链表节点
/// </summary>
public class LinkTableNode
{
/// <summary>
/// 下一个节点
/// </summary>
public LinkTableNode Next
{
get;
set;
}
/// <summary>
/// 上一个节点
/// </summary>
public LinkTableNode Previous
{
get;
set;
}
}
}