使用C#链表简单实现的约瑟夫环

前几天随便用C#写了一个约瑟夫环 
谈不上效率 因为使用的是C#自带的双向链表

 1  //count  代表总数
      
//order  代表报号出列的号码
       //begId  代表起始 位置
         class Program
 2    {
 3        static void Main(string[] args)
 4        {
 5            Console.WriteLine("Please Enter Total:");
 6            int count = int.Parse(Console.ReadLine());
 7
 8            LinkedList<Person> list = InitList(count);
 9
10            Console.WriteLine("Please Enter Index:");
11            int order = int.Parse(Console.ReadLine());
12
13            Console.WriteLine("Please Enter Start Index:");
14            int begid = int.Parse(Console.ReadLine());
15
16
17            LinkedListNode<Person> first = list.First;
18            for (int i = 0; i < begid - 1; i++)
19                first = (first == list.Last ? list.First : first.Next);
20
21            LinkedListNode<Person> start;
22            do
23            {
24                for (int i = 0; i < order - 1; i++)
25                    first = (first == list.Last ? list.First : first.Next);
26
27                start = first;
28
29                first = (first == list.Last ? list.First : first.Next);
30                
31                Console.WriteLine(start.Value.Id);
32                list.Remove(start);
33            }

34            while (list.Count >= 1);
35
36            Console.ReadLine();
37        }

38
39        static LinkedList<Person> InitList(int count)
40        {
41            LinkedList<Person> list = new LinkedList<Person>();
42            for (int i = 1; i <= count; i++)
43            {
44                Person p = new Person();
45                p.Id = i;
46                p.Name = "Person-" + i.ToString();
47                list.AddLast(p);
48            }

49            return list;
50        }

51    }

52
53    class Person
54    {
55        private int _id;
56
57        public int Id
58        {
59            get return _id; }
60            set { _id = value; }
61        }

62        private string _name;
63
64        public string Name
65        {
66            get return _name; }
67            set { _name = value; }
68        }

69    }

70

运行结果如下:




posted @ 2008-04-09 10:11  文浩的随笔  阅读(1436)  评论(0编辑  收藏  举报