Reversing a Linked List

Paresh Krishna Sharma
3 min readJun 30, 2023

A Simple Algorithm with Time and Space Complexity Analysis

A linked list is a data structure composed of nodes, where each node contains a value and a pointer to the next node in the list. Reversing a linked list involves changing the direction of pointers, so the first node becomes the last, the second node becomes the second last, and so on. In this article, we will explore a simple algorithm to reverse a linked list and analyze its time and space complexity.

Example of Linked list reversing

Algorithm

The algorithm to reverse a linked list can be implemented iteratively or recursively. Here, we will focus on the iterative approach as it is more straightforward and efficient in terms of space complexity.

Let’s consider a linked list with the following structure:

class Node:
def __init__(self, data):
self.data = data
self.next = None

To reverse the linked list, we will maintain three pointers: `current`, `previous`, and `next`. We will iterate through the linked list, updating the pointers as follows:

  1. Initialize `current` as the head of the linked list and `previous` and `next` as `None`.
  2. Traverse the list using a loop until `current` becomes `None`.
  3. Within each iteration, store the next node of `current`

--

--

Paresh Krishna Sharma
Paresh Krishna Sharma

Written by Paresh Krishna Sharma

Unleashing the Power of Code, Data, and Creativity ✨ | Software Engineer at Microsoft | LinkedIn : www.linkedin.com/in/itsparesh

Responses (1)