题解 | #链表中的节点每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
        if head is None:
            return head

		# 遍历链表,获取值
        a = []
        tmp = head
        while head != None:
            a.append(head.val)
            head = head.next
        
		# 获取分组数
        time = len(a)//k

		# 当需要组内成员数大于链表成员数时,直接返回原链表,不需要翻转
        if len(a) < k:
            return tmp
		# 否则,将第一个组的最后一个元素作为新链表的首位元素
        else:
            newL = ListNode(a[k-1])

		# 创建新链表
        res = newL
        b = a[0: k-1][::-1]
        for i in range(time):
            for j in b:
                newL.next = ListNode(j)
                newL = newL.next
            b = a[(i+1)*k: (i+1)*k+k][::-1]
        
        for j in a[time*k:]:
            newL.next = ListNode(j)
            newL = newL.next
        
        newL.next = None
        return res

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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