Ejemplo n.º 1
0
        public static void KickoutByLink(JosephusNode head)
        {
            #region 单循环链表的实现

            //var pre = head;
            //var curr = head;
            //int count = 1;
            //while (null != curr)
            //{
            //    if (count == 3)
            //    {
            //        Console.WriteLine("出圈{0}:", curr.Index);
            //        pre.Next = curr.Next;
            //        count = 0;
            //    }
            //    pre = curr;
            //    curr = curr.Next;
            //    count++;

            //    if (pre == curr)
            //    {
            //        Console.WriteLine("留下{0}:", curr.Index);
            //        break;
            //    }
            //}

            #endregion

            #region 双向循环链表的实现

            var curr = head;
            int count = 1;
            while (curr.Next != curr)
            {
                if (count == 3)
                {
                    Console.WriteLine("出圈{0}:", curr.Index);
                    curr.Prev.Next = curr.Next;
                    curr.Next.Prev = curr.Prev;
                    count = 0;
                }

                curr = curr.Next;
                count++;
            }

            Console.WriteLine("留下{0}:", curr.Index);

            #endregion
        }
Ejemplo n.º 2
0
        public static JosephusNode BuildLinkedList(List<int> kids)
        {
            var head = new JosephusNode()
            {
                Prev = null,
                Next = null,
                Index = 0
            };

            //声明临时节点,用于循环构建链表
            var tmp = head;

            //该临时节点与head相连
            head.Next = tmp;
            tmp.Prev = head;

            for (var i = 0; i < kids.Count(); i++)
            {
                if (i == 0)
                {
                    head.Index = kids[i];
                }
                else
                {
                    tmp.Next = new JosephusNode()
                    {
                        Prev = tmp,
                        Next = null,
                        Index = kids[i]
                    };
                    tmp = tmp.Next;
                }
            }

            //最后一个节点与head相连
            tmp.Next = head;
            head.Prev = tmp;

            return head;
        }