Example #1
0
        public void TestIntersectionofTwoLinkedLists()
        {
            var list = BuildNode1();
            var r    = IntersectionofTwoLinkedLists.GetIntersection1(list[0], list[1]);

            Assert.AreEqual(r.Val, 5);

            list = BuildNode2();
            r    = IntersectionofTwoLinkedLists.GetIntersection1(list[0], list[1]);
            Assert.AreEqual(r, null);
        }
        public void TestMethod2(int intersectVal, int[] listA, int[] listB, int skipA, int skipB, int expected)
        {
            // Arrange
            IntersectionofTwoLinkedLists question = new IntersectionofTwoLinkedLists();

            ListNode headA = null;
            ListNode headB = null;

            if (intersectVal == 0)
            {
                if (listA != null && listA.Length > 0)
                {
                    headA = new ListNode(listA[0]);
                    ListNode node = headA;

                    for (int i = 1; i < listA.Length; i++)
                    {
                        node.next = new ListNode(listA[i]);
                        node      = node.next;
                    }
                }

                if (listB != null && listB.Length > 0)
                {
                    headB = new ListNode(listB[0]);
                    ListNode node = headB;

                    for (int i = 1; i < listB.Length; i++)
                    {
                        node.next = new ListNode(listB[i]);
                        node      = node.next;
                    }
                }
            }
            else
            {
                ListNode intersectionHead = null;

                if (listA != null && listA.Length > 0)
                {
                    headA = new ListNode(listA[0]);
                    ListNode node = headA;

                    for (int i = 1; i < listA.Length; i++)
                    {
                        node.next = new ListNode(listA[i]);
                        node      = node.next;

                        if (i == skipA)
                        {
                            intersectionHead = node;
                        }
                    }
                }

                if (listB != null && listB.Length > 0)
                {
                    headB = new ListNode(listB[0]);
                    ListNode node = headB;

                    for (int i = 1; i < skipB && i < listB.Length; i++)
                    {
                        node.next = new ListNode(listB[i]);
                        node      = node.next;
                    }

                    node.next = intersectionHead;
                }
            }

            // Act
            ListNode actual = question.GetIntersectionNode2(headA, headB);

            // Assert
            Assert.AreEqual(expected, actual == null ? -1 : actual.val);
        }