# 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

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):
for element in elements[1:]:
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)

print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')

class Solution:
def solve(self, node, i, j):

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

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