[python] Reverse Nodes in K Group

Viewer

copydownloadembedprintName: Reverse Nodes in K Group
  1. def reverseKGroup(head, k):
  2.     dummy = jump = ListNode(0)
  3.     dummy.next = left = right = head
  4.  
  5.     while True:
  6.         count = 0
  7.         while right and count < k:   # use right to locate the range
  8.             right = right.next
  9.             count += 1
  10.         if count == k:  # if size k satisfied, reverse the inneright linked list
  11.             pre, cur = right, left
  12.             for _ in range(k):
  13.                 cur.next, cur, pre = pre, cur.next, cur  # standard reversing
  14.             jump.next, jump, left= pre, left, right  # connect two k-groups
  15.         else:
  16.             return dummy.next

Editor

You can edit this paste and save as new:


File Description
  • Reverse Nodes in K Group
  • Paste Code
  • 12 Feb-2021
  • 613 Bytes
You can Share it: