题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @param k int整型 # @return ListNode类 # class Solution: def reverseKGroup(self , head: ListNode, k: int) -> ListNode: # write code here n, cur = 0, head while cur: n += 1 cur = cur.next dummy = ListNode(0) dummy.next = head p0 = dummy prev, cur = None, p0.next while n >= k: n -= k for _ in range(k): nxt = cur.next cur.next = prev prev = cur cur = nxt nxt = p0.next p0.next.next = cur p0.next = prev p0 = nxt return dummy.next
算法刷题记录 文章被收录于专栏
刷题,记录牛客的101