题解 | #链表中的节点每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 k <= 0 : #防护非法输入 return head if not head : #防护空输入 return head if head.next == None : #防护特殊输入 return head # 基本思路:将列表用临时数组保存,利用python切片反转,完成后将反转之后的数组组装为列表 temp_list = [] while head: temp_list.append(head.val) head = head.next result_list = [] manstart_index = 0 manend_index = manstart_index + k while True: if manend_index > len(temp_list): result_list.append(temp_list[manstart_index:]) break result_list.append(temp_list[manstart_index:manend_index][::-1]) manstart_index += k manend_index = manstart_index + k rvs_list = [] for i in result_list: rvs_list += i result = ListNode(-1) pre_node = result for i in rvs_list: pre_node.next = ListNode(i) pre_node = pre_node.next return result.next