BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features53 of 54 in topic

842. Reverse a singly linked list in place

EasyData processing and features

A log buffer is kept as a singly linked list from oldest to newest, and you need it newest first without allocating new nodes.

A node class is provided: ListNode(val, next=None). Write reverse_list(head) that reverses the list in place and returns the new head. The input can be None.

Functiondef reverse_list(head)

Example 1

1 -> 2 -> 3 becomes 3 -> 2 -> 1.

Example 2

Input: to_list(reverse_list(build([9])))

Output: [9]

Example 3

Input: to_list(reverse_list(build([4, 5])))

Output: [5, 4]

Constraints

  • 0 <= list length <= 100,000
Hint 1

prev starts as None.

Hint 2

Save current.next before overwriting it.

Hint 3

Return prev at the end.

Common mistakes
  • Overwriting next before saving it, which cuts off the rest of the list.
  • Returning the old head.
  • Using recursion on a very long list.
Understand the idea

In-place list reversal is a three-pointer walk: previous, current and next. Each step flips one arrow. For 1 -> 2 -> 3: flip 1 to point at None, then 2 to point at 1, then 3 to point at 2, and return 3. A recursive version is shorter but uses O(n) stack, which can overflow on long lists.

Topics
Data processing and features
Similar questions
  • Standardise features without leaking test dataEasy
  • Scale features with the median and IQR so outliers do not dominateEasy
  • Encode hour of day and day of week as sine and cosine featuresEasy
  • Clip outliers using percentiles learned on the training set onlyEasy
All Data processing and features problems
Report
842 / 903
Python 3solution.pyPython idle
1
2
3
4
5
# ListNode(val, next=None) is provided
def reverse_list(head):
# return the new head
pass
​
to_list(reverse_list(build([1, 2, 3])))

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 6 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS