Tutorialspoint
Problem
Solution
Submissions

Reverse LinkedList

Certification: Basic Level Accuracy: 83.33% Submissions: 6 Points: 5

Write a Java program to reverse a singly linked list. Return the head of the reversed list.

Example 1
  • Input: head = [1,2,3,4,5]
  • Output: [5,4,3,2,1]
  • Explanation:
    • Reverse each link → end becomes new head
Example 2
  • Input: head = [1,2]
  • Output: [2,1]
Constraints
  • 0 ≤ nodes ≤ 5000
  • -5000 ≤ Node.val ≤ 5000
  • Time Complexity: O(n)
  • Space Complexity: O(1)
Linked ListHCL TechnologiesSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the iterative approach with three pointers: prev, current, and next.
  • Maintain these pointers to reverse the links between nodes.
  • Start with prev as null and current as head.
  • For each node, store the next node, reverse the link, and update pointers.
  • Return prev as the new head after the traversal.

Steps to solve by this approach:

 Step 1: Initialize three pointers: prev = null, current = head, and next = null.

 Step 2: Iterate through the linked list until current becomes null.
 Step 3: Inside the loop, first store the next node: next = current.next.
 Step 4: Reverse the current node's pointer: current.next = prev.
 Step 5: Move prev and current one step forward: prev = current and current = next.
 Step 6: After the loop ends, prev will be pointing to the new head of the reversed list.
 Step 7: Return prev as the new head of the reversed linked list.

Submitted Code :