Google Interview Question
Software EngineersCountry: United States
The task was to reverse list, not to return a reversed list so I'm assigning the result to Head. Written in C# 7.3
class Node
{
public Node (String data, Node next)
{
Data = data;
Next = next;
}
public string Data { get; set; }
internal Node Next { get; set; }
}
class LinkedList
{
public Node Head { get; set; }
public void Reverse()
{
if (Head == null) return;
Node currHead = Head, nextNode = null, newList = null;
while (currHead != null)
{
nextNode = currHead.Next;
currHead.Next = newList;
newList = currHead;
currHead = nextNode;
}
Head = newList;
}
}
For the definition of node in linked list given by:
The code for reversing it in linear time is:
- varshaneya June 06, 2018