- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to reverse a linked list in Python
Suppose we have a linked list, we have to reverse it. So if the list is like 2 -> 4 -> 6 -> 8, then the new reversed list will be 8 -> 6 -> 4 -> 2.
To solve this, we will follow this approach −
- Define one procedure to perform list reversal in recursive way as solve(head, back)
- if head is not present, then return head
- temp := head.next
- head.next := back
- back := head
- if temp is empty, then return head
- head := temp
- return solve(head, back)
Let us see the following implementation to get better understanding −
Example
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution(object): def reverseList(self, head): return self.solve(head,None) def solve(self, head, back): if not head: return head temp= head.next head.next = back back = head if not temp: return head head = temp return self.solve(head,back) list1 = make_list([5,8,9,6,4,7,8,1]) ob1 = Solution() list2 = ob1.reverseList(list1) print_list(list2)
Input
[5,8,9,6,4,7,8,1]
Output
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]
- Related Articles
- Program to reverse inner nodes of a linked list in python
- Reverse Linked List in Python
- Golang Program to reverse a given linked list.
- C Program for Reverse a linked list
- Python Program to Reverse only First N Elements of a Linked List
- Program to reverse linked list by groups of size k in Python
- Python Program to Display the Nodes of a Linked List in Reverse using Recursion
- Python Program to Display the Nodes of a Linked List in Reverse without using Recursion
- How to Reverse a linked list in android?
- Python program to Reverse a range in list
- C Program to reverse each node value in Singly Linked List
- Program to reverse a list by list slicing in Python
- Reverse a Linked List using C++
- Python program to create a doubly linked list of n nodes and display it in reverse order
- Python program to create a Circular Linked List of n nodes and display it in reverse order

Advertisements