2074.反转偶数长度组的节点

https://leetcode-cn.com/problems/reverse-nodes-in-even-length-groups/

用两重循环控制,反转结点用修改节点值实现,减少链表操作

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
        Head = ListNode(0)
        Head.next= head	#辅助头结点
        p = Head	#标记每组的头
        n = 1		#每组的节点数,从1开始递增
        
        while p.next:
            cnt = 0
            q = p		#往前探测每组的尾
            vals = []	#记录改组的每个节点值
            # 从p开始往前遍历n个结点
            while q.next and cnt < n:
                q = q.next
                cnt += 1
                vals.append(q.val)
            if cnt % 2 == 0:	#若结点长度为偶数,进行反转
                vals = vals[::-1]
                s = p.next	#工作节点
                for i in range(cnt):
                    s.val = vals[i]
                    s = s.next
            p = q		#为下一组做准备
            n += 1
        return Head.next

最后更新于