Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse Linked List Iteratively

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

Your question is Reverse Linked List Iteratively. 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

Brillio workflow services may represent processing stages as a singly linked list. Implement a function that reverses the list in place, supporting both an iterative pointer-based approach and a recursive approach.

Formal Specification

Define a ListNode with an integer val field and a next pointer. Implement reverse_linked_list(head, recursive):

  1. head is the first ListNode, or None for an empty list.
  2. When recursive is False, reverse the list iteratively.
  3. When recursive is True, reverse the list recursively.
  4. Return the new head of the reversed list.
  5. Do not allocate new list nodes. The existing nodes must be relinked in place.

For test-case serialization, an input array represents the linked list values, and the expected array represents the values obtained by traversing the returned list.

Constraints

  • 0 <= n <= 10^5
  • -10^9 <= node.val <= 10^9
  • The list is singly linked
  • Existing nodes must be reused

Function Signature

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