题解 | #链表中的节点每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 PrintList(self, head):
        test_cur = head
        while test_cur:
            print(test_cur.val, end=" ")
            test_cur = test_cur.next
        print()

    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        # write code here
        phead = ListNode(-1)
        phead.next = head
        len_cur = head
        c = 0
        while len_cur:
            len_cur = len_cur.next
            c += 1
        div = c // k
        pre = phead
        cur = head
        for _ in range(div):
            for _ in range(k - 1):
                temp = cur.next
                cur.next = temp.next
                temp.next = pre.next
                pre.next = temp
            pre = cur
            cur = cur.next
        head = phead.next
        del phead
        return head

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务