Reverse a Linked List Python (original) (raw)

Last Updated : 20 Jan, 2026

Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes.

**For Example:

**Input:

reverse_a_linked_list_2

Input linked list

**Output:

Reverse-a-Linked-List-2

Output - Reversed Linked List

Let's look at the ways to achieve this in Python:

1. Iterative Method

The idea is to reverse the links of all nodes using threepointers:

Starting from the first node, initialize curr with the head of linked list and **next with the next node of curr. Update the next pointer of currwith prev. Finally, move the three pointer by updating prevwith currand currwith next.

Python `

Class to represent node of linked list

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

Class to define linked list

class LinkedList: def init(self): self.head = None

def push(self, new_data):
    new_node = Node(new_data)
    new_node.next = self.head
    self.head = new_node

def printList(self):
    temp = self.head
    while(temp):
        print (temp.data,end=" ")
        temp = temp.next

Creating a linked list and adding elements to it

ll = LinkedList() ll.push(20) ll.push(4) ll.push(15) ll.push(85)

print ("Given Linked List:") ll.printList()

prev = None curr = ll.head while(curr is not None): next = curr.next curr.next = prev prev = curr curr = next ll.head = prev

print ("\nReversed Linked List:") ll.printList()

`

Output

Given Linked List 85 15 4 20 Reversed Linked List 20 4 15 85

**Explanation:

2. Recursive Method

The idea is to reach the last node of the linked list using recursion then start reversing the linked list from the last node.

Python `

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

class LinkedList: def init(self): self.head = None

def reverseUtil(self, curr, prev):
    if curr.next is None:
        self.head = curr
        curr.next = prev
        return

    next = curr.next
    curr.next = prev
    self.reverseUtil(next, curr)

def reverse(self):
    if self.head is None:
        return
    self.reverseUtil(self.head, None)

def push(self, new_data):
    new_node = Node(new_data)
    new_node.next = self.head
    self.head = new_node

def printList(self):
    temp = self.head
    while(temp):
        print(temp.data,end=" ")
        temp = temp.next

ll = LinkedList() ll.push(5) ll.push(4) ll.push(3) ll.push(2) ll.push(1)

print("Given linked list") ll.printList()

ll.reverse()

print("\nReverse linked list") ll.printList()

`

Output

Given linked list 1 2 3 4 5 Reverse linked list 5 4 3 2 1

**Explanation:

Please refer Reverse a linked list for more details!