Reverse Linked List in Python


Suppose we have a linked list, we have to reverse it. So if the list is like 1 → 3 → 5 → 7, then the new reversed list will be 7 → 5 → 3 → 1

To solve this, we will follow this approach −

  • Define one procedure to perform list reversal in a recursive way as to solve(head, back)
  • if the 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)

Example

Let us see the following implementation to get a better understanding −

 Live Demo

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):
      """
      :type head: ListNode
      :rtype: ListNode
      """
      return self.solve(head,None)
   def solve(self, head, back):
      if not head:
         return head
      temp= head.next
      #print(head.val)
      head.next = back
      back = head
      if not temp:
         return head
      head = temp
      return self.solve(head,back)
list1 = make_list([1,3,5,7])
ob1 = Solution()
list2 = ob1.reverseList(list1)
print_list(list2)

Input

list1 = [1,3,5,7]

Output

[7, 5, 3, 1, ]

Updated on: 28-Apr-2020

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements