题解 | #链表中的节点每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

全部评论

相关推荐

头像
11-09 17:30
门头沟学院 Java
TYUT太摆金星:我也是,好几个华为的社招找我了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务