【LeetCode】25.K 个一组翻转链表

25.K 个一组翻转链表

知识点:链表

题目描述

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

示例 3:
输入:head = [1,2,3,4,5], k = 1
输出:[1,2,3,4,5]


解法一:迭代

这道题目其实是206.反转链表的进阶,我们需要以k个节点的数量为一组,然后进行反转
所以自然的思路就是将整个链表分组,每组都是k个节点,然后将这组的链表进行反转
在这之后,我们需要将这个翻转后的链表和之前一组的尾部节点连接在一起,然后将当前这组的尾部节点和下一组的头部节点连接在一起,所以需要记录上一个组的尾部节点。
写翻转链表的函数,传进去头结点和尾节点,然后返回新的头结点和尾节点,

# 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: Optional[ListNode], k: int) -> Optional[ListNode]:
        dummyhead = ListNode(0)
        dummyhead.next = head   # head为当前要反转链表的头
        pre = dummyhead   # pre为前一个链表的末尾
        while head:
            tail = pre
            for i in range(k):
                tail = tail.next
                if not tail:
                    return dummyhead.next
            nex = tail.next  #先记录下来
            head, tail = self.reverselist(head, tail)  #反转链表
            pre.next = head
            tail.next = nex
            pre = tail
            head = tail.next
        return dummyhead.next

    def reverselist(self, head, tail):
        dummyhead = head
        pre = head
        cur = head.next
        if not pre or not cur:
            return pre, pre
        while pre != tail:
            nex = cur.next
            cur.next = pre
            pre, cur = cur, nex
        return pre, dummyhead  #返回新的头尾节点
posted @ 2022-04-13 11:29  Curryxin  阅读(38)  评论(0编辑  收藏  举报
Live2D