Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            SingleLinkNode first = new SingleLinkNode(1);
            SingleLinkNode node2 = new SingleLinkNode(2);
            SingleLinkNode node3 = new SingleLinkNode(3);
            SingleLinkNode node4 = new SingleLinkNode(4);
            SingleLinkNode node5 = new SingleLinkNode(5);
            SingleLinkNode node6 = new SingleLinkNode(6);

            first.Next = node2;
            node2.Next = node3;
            node3.Next = node4;
            node4.Next = node5;
            node5.Next = node6;

            SingleLinkNode second = new SingleLinkNode(11);
            SingleLinkNode node10 = new SingleLinkNode(10);
            SingleLinkNode node9  = new SingleLinkNode(9);
            SingleLinkNode node8  = new SingleLinkNode(8);

            second.Next = node10;
            node10.Next = node9;
            node9.Next  = node8;

            node8.Next = node3;

            SingleLinkNode crossNode = first.FindCrossNode(second);

            Console.WriteLine(crossNode.Data);
        }
Ejemplo n.º 2
0
        public SingleLinkNode FindCrossNode(SingleLinkNode secondLinkNode)
        {
            if (secondLinkNode != null)
            {
                int currentLength = 0;
                int secondLength  = 0;

                SingleLinkNode first  = this;
                SingleLinkNode second = secondLinkNode;

                while (first != null)
                {
                    currentLength++;
                    first = first.Next;
                }

                while (second != null)
                {
                    secondLength++;
                    second = second.Next;
                }

                first  = this;
                second = secondLinkNode;

                // 当前的链表比较长,我们先把差值的步数先走掉
                // 然后齐步走
                if (currentLength > secondLength)
                {
                    int gap = currentLength - secondLength;

                    while (gap > 0)
                    {
                        first = first.Next;
                        gap--;
                    }
                }
                // 先走secondlinknode, 然后齐步走
                else
                {
                    int gap = secondLength - currentLength;

                    while (gap > 0)
                    {
                        second = second.Next;
                        gap--;
                    }
                }

                while (first != null && second != null && first != second)
                {
                    first  = first.Next;
                    second = second.Next;
                }

                if (first == second)
                {
                    return(first);
                }
            }

            return(null);
        }