Open In App

Python Program to Reverse a linked list

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples: 

Input : Head of following linked list  
       1->2->3->4->NULL
Output : Linked list should be changed to,
       4->3->2->1->NULL

Input : Head of following linked list  
       1->2->3->4->5->NULL
Output : Linked list should be changed to,
       5->4->3->2->1->NULL

Input : NULL
Output : NULL

Input  : 1->NULL
Output : 1->NULL

Iterative Method  

Python3




# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(n) as 'next' 
#variable is getting created in each loop.
  
# Node class
  
  
class Node:
  
    # Constructor to initialize the node object
    def __init__(self, data):
        self.data = data
        self.next = None
  
  
class LinkedList:
  
    # Function to initialize head
    def __init__(self):
        self.head = None
  
    # Function to reverse the linked list
    def reverse(self):
        prev = None
        current = self.head
        while(current is not None):
            next = current.next
            current.next = prev
            prev = current
            current = next
        self.head = prev
  
    # Function to insert a new node at the beginning
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
  
    # Utility function to print the LinkedList
    def printList(self):
        temp = self.head
        while(temp):
            print (temp.data,end=" ")
            temp = temp.next
  
  
# Driver program to test above functions
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
  
print ("Given Linked List")
llist.printList()
llist.reverse()
print ("\nReversed Linked List")
llist.printList()
  
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


Output: 

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

Time Complexity: O(N)

Auxiliary Space: O(1)

A Simpler and Tail Recursive Method 

Python3




# Simple and tail recursive Python program to
# reverse a linked list
  
# Node class
  
  
class Node:
  
    # Constructor to initialize the node object
    def __init__(self, data):
        self.data = data
        self.next = None
  
  
class LinkedList:
  
    # Function to initialize head
    def __init__(self):
        self.head = None
  
    def reverseUtil(self, curr, prev):
  
        # If last node mark it head
        if curr.next is None:
            self.head = curr
  
            # Update next to prev node
            curr.next = prev
            return
  
        # Save curr.next node for recursive call
        next = curr.next
  
        # And update next
        curr.next = prev
  
        self.reverseUtil(next, curr)
  
    # This function mainly calls reverseUtil()
    # with previous as None
  
    def reverse(self):
        if self.head is None:
            return
        self.reverseUtil(self.head, None)
  
    # Function to insert a new node at the beginning
  
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
  
    # Utility function to print the LinkedList
    def printList(self):
        temp = self.head
        while(temp):
            print(temp.data,end=" ")
            temp = temp.next
  
  
# Driver program
llist = LinkedList()
llist.push(8)
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
  
print("Given linked list")
llist.printList()
  
llist.reverse()
  
print("\nReverse linked list")
llist.printList()
  
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


Output

Given linked list
1 2 3 4 5 6 7 8 
Reverse linked list
8 7 6 5 4 3 2 1 

Time Complexity: O(N)

Auxiliary Space: O(1)

Please refer complete article on Reverse a linked list for more details!
 



Previous Article
Next Article

Similar Reads

Python Program For Printing Reverse Of A Linked List Without Actually Reversing
Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorithm: printReverse(head) 1. call print reverse for h
2 min read
Python Program For Merging Two Sorted Linked Lists Such That Merged List Is In Reverse Order
Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order). Examples: Input: a: 5->10->15->40 b: 2->3->20 Output: res: 40->20->15->10->5->3->2 Input: a: NULL b: 2->3->20 Output: res: 20->3->2Recommended: Please solve it on "PRACTIC
4 min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Python program to Reverse a range in list
Given a List, our task is to write a Python program to reverse a range in the list. Reverse a range in a list Example Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 3, 9Output : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]Explanation : 8, 9, 2, 10, 12, 7 are reversed in list to 7, 12, 10, 2, 9, 8. Input : test_list = [6, 3, 1, 8, 9, 2
5 min read
Python Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4 Recommended: Please sol
3 min read
Python3 Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Python | Reverse sequence of strictly increasing integers in a list
Given a list of integers, write a Python program to reverse the order of consecutively incrementing chunk in given list. Examples: Input : [0, 1, 9, 8, 7, 5, 3, 14] Output : [9, 1, 0, 8, 7, 5, 14, 3] Explanation: There are two chunks of strictly increasing elements (0, 1, 9) and (3, 14). Input : [-5, -3, 0, 1, 3, 5, -2, -12] Output : [5, 3, 1, 0, -
3 min read
Python | Reverse each tuple in a list of tuples
Given a list of tuples, write a Python program to reverse each tuple in the given list of tuples. Examples: Input : [(1, 2), (3, 4, 5), (6, 7, 8, 9)] Output : [(2, 1), (5, 4, 3), (9, 8, 7, 6)] Input : [('a', 'b'), ('x', 'y'), ('m', 'n')] Output : [('b', 'a'), ('y', 'x'), ('n', 'm')] Method #1 : Negative-step slicing We can use standard negative-ste
5 min read
Python | Reverse sign of each element in given list
Given a list of integers, write a Python program to reverse the sign of each element in given list. Examples: Input : [-1, 2, 3, -4, 5, -6, -7] Output : [1, -2, -3, 4, -5, 6, 7] Input : [-5, 9, -23, -2, 7] Output : [5, -9, 23, 2, -7] Methods #1: List comprehension C/C++ Code # Python3 program to Convert positive # list integers to negative and vice
3 min read
Python | Reverse Order Sort in String List
Sometimes, while working with Python, we can have a problem in which we need to perform the reverse sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + sorted() + join()
3 min read