コード例 #1
0
        public void LinkedListIntv_CopyRandomListTest1()
        {
            RandomListNode l0 = new RandomListNode(0),
           l1 = new RandomListNode(1),
           l2 = new RandomListNode(2),
           l3 = new RandomListNode(3),
           l4 = new RandomListNode(4);

            l0.Next   = l1;
            l1.Next   = l2;
            l2.Next   = l3;
            l3.Next   = l4;
            l0.Random = l2;
            l3.Random = l0;

            RandomListNode r = CopyRandomList(l0);

            Assert.AreEqual(0, r.Label);
            Assert.AreEqual(2, r.Random.Label); r = r.Next;
            Assert.AreEqual(1, r.Label); r        = r.Next;
            Assert.AreEqual(2, r.Label); r        = r.Next;
            Assert.AreEqual(3, r.Label);
            Assert.AreEqual(0, r.Random.Label); r = r.Next;
            Assert.AreEqual(4, r.Label);
        }
コード例 #2
0
        public static RandomListNode CopyRandomList(RandomListNode head)
        {
            if (null == head)
            {
                return(null);
            }

            RandomListNode result   = null,
                           pold     = head,
                           pnew     = result,
                           poldNext = null;

            do
            {
                poldNext  = pold.Next;
                pnew      = new RandomListNode(pold.Label);
                pold.Next = pnew;
                pnew.Next = poldNext;
                if (result == null)
                {
                    result = pnew;
                }
                pold = poldNext;
            }while(pold != null);

            pold = head;
            while (pold != null)
            {
                if (pold.Random != null)
                {
                    pold.Next.Random = pold.Random.Next;
                }
                pold = pold.Next.Next;
            }

            pold = head;
            pnew = result;
            while (pnew.Next != null)
            {
                pold.Next = pnew.Next;
                pold      = pold.Next;
                pnew.Next = pold.Next;
                pnew      = pnew.Next;
            }

            pold.Next = null;
            pnew.Next = null;
            return(result);
        }