Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reversing a Linked List

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Reversing a Linked List. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Flexport may store shipment events in chronological order as a singly linked list. Given the head of this list, reverse the list in place so the most recent event becomes the first node.

Implement reverse_linked_list(head) and return the new head. Each node has a value field and a next pointer. The evaluator constructs the linked list before calling your function and serializes the returned list back to an array of values for verification.

Your solution must relink existing nodes rather than create replacement nodes. Handle empty lists and lists containing a single node.

Formal Specification

  • Input: head, either None or a reference to the first ListNode in a singly linked list.
  • Output: A reference to the new head after reversing every next pointer.
  • Node structure: Each ListNode contains value and next.

Constraints

  • 0 <= n <= 10^5
  • Node values may be any Python object
  • The list is singly linked and contains no cycle
  • Modify existing nodes in place
  • Use O(1) auxiliary space

Function Signature

def reverse_linked_list(head):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output