我正在尝试解决这个问题
https://leetcode.com/explore/interview/card/top-interview-questions-medium/107/linked-list/785
我写了我的代码,我正在尝试对其进行测试
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
}
}
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/107/linked-list/785
/// </summary>
[TestClass]
public class GetIntersectionNodeTest
{
/// <summary>
/// intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
/// </summary>
[TestMethod]
public void TestMethod1()
{
ListNode listA = new ListNode(4);
listA.next = new ListNode(1);
listA.next.next = new ListNode(8);
listA.next.next.next = new ListNode(4);
listA.next.next.next.next = new ListNode(5);
ListNode listB = new ListNode(5);
listB.next = new ListNode(0);
listB.next.next = new ListNode(1);
listB.next.next.next = new ListNode(8);
listB.next.next.next.next = new ListNode(4);
listB.next.next.next.next.next = new ListNode(5);
GetIntersectionNodeClass intersection= new GetIntersectionNodeClass();
ListNode res = intersection.GetIntersectionNode(listA, listB);
Assert.AreEqual(8,res.val);
}
}
public class GetIntersectionNodeClass
{
public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
{
if (headA == null || headB == null)
{
return null;
}
ListNode currA = headA;
ListNode currB = headB;
while (currA != currB)
{
if (currA == null)
{
currA = headB;
}
else
{
currA = currA.next;
}
if (currB == null)
{
currB = headA;
}
else
{
currB = currB.next;
}
}
return currA;
}
}
}
我的代码适用于leetcode,但是根据他们的示例,我尝试为其编写一个单元测试。但是我的代码返回null而不是预期的结果。 我想我缺少一些IComparable比较,但是为什么它对Leetcode有效? 谢谢
答案 0 :(得分:0)
这是针对“ Some Programmer dude”建议的测试的修正
[TestMethod]
public void TestMethod1()
{
ListNode listA = new ListNode(4);
listA.next = new ListNode(1);
listA.next.next = new ListNode(8);
listA.next.next.next = new ListNode(4);
listA.next.next.next.next = new ListNode(5);
ListNode listB = new ListNode(5);
listB.next = new ListNode(0);
listB.next.next = new ListNode(1);
listB.next.next.next = listA.next.next;
listB.next.next.next.next = listA.next.next.next;
listB.next.next.next.next.next = listA.next.next.next.next;
GetIntersectionNodeClass intersection= new GetIntersectionNodeClass();
ListNode res = intersection.GetIntersectionNode(listA, listB);
Assert.AreEqual(8,res.val);
}