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:
Let us see the following implementation to get better understanding:
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements) 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))
[1,2,3,4,5,6,7,8,9], 2, 6
[1, 2, 7, 6, 5, 4, 3, 8, 9, ]