
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,]
Advertisements