边工作边刷题:70天一遍leetcode: day 37-2
Reverse Nodes in k-Group
思路:这题最主要是犁清对每组操作的时更新链表指针的顺序。对每个group要记录pre,cur,tail。一种错误的记忆是仿照reverse把cur.next=pre。实际中只有group内reverse,对group外(i.e., pre和tail.next), 想象成做rotation: pre要链接原来的tail,而原来的head去链接tail.next。
k-Group内循环移动几步?这里思维的要点是counter表示的是移动的步数而不是结点数。当前group head移动k步,就会移到下一组的head
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
def reverseOne(head, tail):
cur = head
pre = None
while cur!=tail:
next=cur.next
cur.next=pre
pre=cur
cur=next
return pre
dummy = ListNode(0)
dummy.next = head
cur = head
tail = head
pre = dummy
while tail:
n=k
while tail and n>0:
tail=tail.next
n-=1
if n!=0:
break
ch = reverseOne(cur, tail)
pre.next = ch
cur.next = tail
pre = cur
cur = tail
return dummy.next