题解 | #链表中的节点每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 not head or not head.next or k == 1:
return head
count = 1
pre, cur, nxt = None, head, head.next
stack = []
while nxt:
stack.append(cur)
if count % k == 0:
tmp_head, tail = self.reverse(stack)
if not pre:
head = tmp_head
else:
pre.next = tmp_head
pre, cur, nxt = tail, tail.next, nxt.next
else:
cur, nxt = cur.next, nxt.next
count += 1
if count % k == 0:
stack.append(cur)
tmp_head, _ = self.reverse(stack)
if not pre:
head = tmp_head
else:
pre.next = tmp_head
return head
def reverse(self, stack: list[ListNode]):
cur = stack.pop()
head = cur
while stack:
nxt = cur.next
tmp = stack.pop()
cur.next = tmp
tmp.next = nxt
cur = cur.next
return head, cur
查看25道真题和解析

