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
Program to reverse linked list by groups of size k in Python
Suppose we have a singly linked list, and another value k, we have to reverse every k contiguous group of nodes.
So, if the input is like List = [1,2,3,4,5,6,7,8,9,10], k = 3, then the output will be [3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]
To solve this, we will follow these steps −
- tmp := a new node with value 0
- next of tmp := node
- prev := null, curr := null
- lp := temp, lc := curr
- cnt := k
- while curr is not null, do
- prev := null
- while cnt > 0 and curr is not null, do
- following := next of curr
- next of curr := prev
- prev := curr, curr := following
- cnt := cnt - 1
- next of lp := prev, next of lc := curr
- lp := lc, lc := curr
- cnt := k
- return next of tmp
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:
def solve(self, node, k):
tmp = ListNode(0)
tmp.next = node
prev, curr = None, node
lp, lc = tmp, curr
cnt = k
while curr:
prev = None
while cnt > 0 and curr:
following = curr.next
curr.next = prev
prev, curr = curr, following
cnt -= 1
lp.next, lc.next = prev, curr
lp, lc = lc, curr
cnt = k
return tmp.next
ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9,10])
print_list(ob.solve(head, 3))
Input
[1,2,3,4,5,6,7,8,9,10], 3
Output
[3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]
Advertisements