题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=295&tqId=722&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
# 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 ''' 先统计链表的长度,然后算一下能有几个k,记作n,然后我们要进行n次循环,执行n次相同的遍历,每次遍历,遍历k个元素就结束,将遍历的元素翻转,存放到list中, ''' result = ListNode(-1) result.next = head pre = result count = -1 while pre: pre = pre.next count += 1 n = count // k m = count % k # 重新遍历链表,每k个一组,进行翻转处理 pre = result.next L=[] for i in range(n): tmp=None # 翻转操作 for j in range(k): next = pre.next pre.next = tmp tmp = pre pre = next L.append(tmp) #将最后的不能组成k个元素的链表链条直接添加到list不用翻转 L.append(pre) # 将链表衔接起来,添加一个头节点,result,然后遍历前n-1条链表,将每条链表的尾部纸箱下一条的头部,最后一条不用遍历, result = ListNode(-1) L.insert(0, result) for i in range(len(L)): if i <= len(L)-2: cur = L[i] while cur.next: cur=cur.next cur.next = L[i+1] elif i == len(L)-1: pass return result.next