Program to reverse inner nodes of a linked list in python

PythonServer Side ProgrammingProgramming

Suppose we have linked list, we also have two values i and j, we have to reverse the linked list from i to jth nodes. And finally return the updated list.

So, if the input is like [1,2,3,4,5,6,7,8,9] i = 2 j = 6, then the output will be [1, 2, 7, 6, 5, 4, 3, 8, 9, ]

To solve this, we will follow these steps:

  • prev_head := create a linked list node with value same as null and that points to node
  • prev := prev_head, curr := node
  • iterate through all values from 0 to i, do
    • prev := curr, curr := next of curr
  • rev_before := prev, rev_end := curr
  • Iterate through all values from 0 to (j - i), do
    • tmp := next of curr
    • next of curr := prev
    • prev, curr := curr, tmp
  • next of rev_before := prev, rev_end.next := curr
  • return next of prev_head

Let us see the following implementation to get better understanding:

Example

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:
   def solve(self, node, i, j):
      prev_head = ListNode(None, node)
      prev, curr = prev_head, node

      for _ in range(i):
         prev, curr = curr, curr.next
   
      rev_before, rev_end = prev, curr

      for _ in range(j - i + 1):
         tmp = curr.next
         curr.next = prev
         prev, curr = curr, tmp

      rev_before.next, rev_end.next = prev, curr

      return prev_head.next

ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9])
i = 2
j = 6
print_list(ob.solve(head, i, j))

Input

[1,2,3,4,5,6,7,8,9], 2, 6

Output

[1, 2, 7, 6, 5, 4, 3, 8, 9, ]
raja
Published on 26-Nov-2020 11:41:44
Advertisements