I have written two helpers to make testing easy.
private ListNode GenerateList(int GenerateTo)
{
int i = 1;
ListNode myList = new ListNode(i);
ListNode Tail = myList;
while (i < GenerateTo)
{
i++;
ListNode newTail = new ListNode(i);
Tail.next = newTail;
Tail = Tail.next;
}
return myList;
}
And I have added a method to print the list as an additional method to the ListNode class
public class ListNode
{
int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
public string PrintList()
{
string result = string.Empty;
if (next == null)
result += string.Format("({0}) -> null", val);
else
result += string.Format("({0}) -> ", val) + next.PrintList();
return result;
}
}
This made the tests very simple
[TestMethod]public void TestMethod_Two()
{
ListNode testList = GenerateList(2);
ListNode result = ClassUnderTest.swapPairs(testList);
Assert.AreEqual("(2) -> (1) -> null", result.PrintList());
}
[TestMethod]
public void TestMethod_One()
{
ListNode testList = GenerateList(1);
ListNode result = ClassUnderTest.swapPairs(testList);
Assert.AreEqual("(1) -> null", result.PrintList());
}
My Suggestion that if you want this two work consider Regression as a solution.