I was given 15 minutes to write the code to reverse a singly-linked list.
What do you think of the code style here?
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
[TestClass]
public class ReverseLinkedList
{
[TestMethod]
public void ReservseLinkedListTest()
{
Node<int> head = new Node<int>();
Node<int> two = new Node<int>();
Node<int> three = new Node<int>();
Node<int> four = new Node<int>();
head.Value = 1;
head.Next = two;
two.Value = 2;
two.Next = three;
three.Value = 3;
three.Next = four;
four.Value = 4;
LinkedListHandler.Reserve(ref head);
Assert.AreEqual(4, head.Value);
Assert.AreEqual(3, head.Next.Value);
Assert.AreEqual(2, head.Next.Next.Value);
Assert.AreEqual(1, head.Next.Next.Next.Value);
}
}
public class LinkedListHandler
{
public static void Reserve(ref Node<int> head)
{
Node<int> current = head;
Node<int> previous = null;
while (current != null)
{
Node<int> temp = current.Next;
current.Next = previous;
previous = current;
current = temp;
}
head = previous;
}
}
public class Node<T>
{
public T Value { get; set; }
public Node<T> Next { get; set; }
}
}