Reverse linked list in java


Problem

Given the head of linked list, you need to reverse linked list.

Solution

There are two ways to reverse linked list in java.

  • Iterative
  • Recursive

Reverse a linked list using iterative approach

  • Initialize three pointer prev, curr and next. Assign head to curr.
  • While curr is not null
    • Compute next pointer
    • Assign curr.next to prev.This code will reverse the link.
    • Assign curr to prev and next to curr.In this step, we are moving one node ahead.

Reverse a linked list using recursive approach

You can reverse a linked list using recursive approach too.
Here is simple algorithm for that.

Complete java program to reverse a linked list

That’s all about reversing a linked list in java.

Leave a Reply

Your email address will not be published. Required fields are marked *