leetcode25. k个一组翻转链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/86542384

给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。

示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路比较简单,每k个翻转一次,用递归实现:

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        cur, check, count, cnt = head, head, 0, 0
        while count < k and check:
            check = check.next
            count += 1
        if count == k:
            prev, next_node = None, None
            for i in range(k):  # 翻转
                next_node = cur.next
                cur.next = prev
                prev = cur
                cur = next_node
            if next_node:
                # head为翻转后尾节点
                head.next = self.reverseKGroup(next_node, k)  
            return prev  # prev为翻转后头结点
        else:
            return head

上面用到的额外参数和空间太多了,下面简化后时间也提升了很多,也是用递归的方法,主要先把后面计算出来赋值node,注意while最后会把head赋给node,tmp赋给head,所以出了循环后要把node还给head:

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        node, count = head, 0
        while count < k and node:
            count += 1
            node = node.next
        if count == k:
            node = self.reverseKGroup(node, k)  # 将后面的翻转好作为后续
            while count > 0:  # 翻转
                tmp = head.next
                head.next = node
                node = head
                head = tmp
                count -= 1
            head = node  # 最后把头结点赋给head
        return head

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/86542384
今日推荐