[LeetCode] 25. K个一组翻转链表

·  阅读 94

Description

Linked List


Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        def reverse(f: ListNode, l: ListNode) -> ListNode:
            # reverse ListNode from f to l-1 -> [f, l)
            pre, cur = None, f
            while cur != l:
                next_cur = cur.next
                cur.next = pre
                pre = cur
                cur = next_cur
            return pre
        
        pre_head = ListNode(0, head)
        pre = pre_head
        while head:
            # find the "last" node
            last = head
            for i in range(k):
                if not last: return pre_head.next
                last = last.next
            # reverse slice [head, last)
            new_head = reverse(head, last)
            # patch up reversed slice
            pre.next = new_head
            head.next = last
            # loop into the next circle
            pre = head
            head = last
        return pre_head.next
复制代码
分类:
代码人生
标签:
分类:
代码人生
标签:
收藏成功!
已添加到「」, 点击更改