Reverse a Linked List

Given a singly linked list, write a code to reverse a linked list. In this tutorial, you are going to learn how to reverse a linked list in java using iterative approach.

For example –

Input linked list.

15 -> 9 -> 8 -> 5 -> NULL

When we reverse this linked list then the output is given below.

5 -> 8 -> 9 -> 15 -> NULL

In input linked list, head points to a node whose value is 15 but when it’s reversed the head points to a node whose value is 5.

Reverse a linked list

We can reverse a linked list by using either iterative or recursive approach. In this tutorial, I am going to focus mainly on iterative approach to reverse a singly linked list.

Programming Video Tutorials

Recursion Vs Iteration

Reverse a Linked List in Java

To reverse a linked list in-place, what we have to do is to reverse the pointers such that the next element points to the previous node.

Here are the following steps –

i) Declare three variables previous, curr and temp.

ii) Traverse a linked list while curr is not null. Then Save the next Node of the current element in the temp pointer.

iii) Set the next of the current Node to the previous. Then shift previous to current and current element to temp (which is next).

Remove duplicates from a sorted linked list

I have explained this approach using video tutorial, the link of that video tutorial is present at the end of this post.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

In this video tutorial, I have explained how we can reverse a linked list using iterative approach.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.