Coding problem
Reverse a linked list by relinking its nodes
The task
An editor keeps its undo history as a singly linked list of ListNode, newest first, and a report needs it oldest first.
Complete Reverse(ListNode? head). Reverse the list by changing the nodes' Next links (do not create new nodes) and return the new head. An empty list (null) gives null. The ListNode class is given; do not change it.
Signature
public static ListNode? Reverse(ListNode? head)
Examples
4 → 9 → 1 → 7→7 → 1 → 9 → 4. The last node becomes the head.6 → 3→3 → 6. Two nodes swap places.
Limits: Up to 5,000 nodes.
The tests check: an empty list, one node, repeated values, that the same node objects are reused, that the old head now ends the list, reversing twice, and a list of 5,000 nodes.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
// A node of a singly linked list. Do not change this class: the tests build lists with it.
public sealed class ListNode
{
public int Val;
public ListNode? Next;
public ListNode(int val, ListNode? next = null)
{
Val = val;
Next = next;
}
}
public static class Solution
{
// Reverses the list by relinking its nodes; returns the new head.
public static ListNode? Reverse(ListNode? head)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.