题解 | #链表中的节点每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):
tail=head
for i in range(k):
if tail==None:
return head
tail=tail.next
cur=head
pre=None
while cur!=tail:#翻转链表
nextnode=cur.next
cur.next=pre
pre=cur
cur=nextnode
head.next=self.reverseKGroup(tail,k)#对剩下节点递归,进行每k个链表进行翻转
return pre
查看26道真题和解析