LeetCode25. K个一组翻转链表 python3

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

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

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

当 k = 2 时,应当返回: 2->1->4->3->5

当 k = 3 时,应当返回: 3->2->1->4->5

说明 :

你的算法只能使用常数的额外空间。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

双指针,超时小程序!!!(仅作为思路参考)

class Solution:
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        k1 = self.length(head)//k
        new_head = ListNode(0)
        new_head.next = head
        pre = new_head
        for i in range(k1):
            first = pre.next
            last = pre.next
            while k-1:
                if last.next != None:
                    last = last.next
                    k -= 1
                else:
                    break
            later = last.next
            if last != None and last.next != None:
                first.next = later
                last.next = first
                pre.next = last
                pre = last

        return new_head.next

    def length(self, head):
        cur = head
        count = 0
        while cur:
            cur = cur.next
            count += 1
        return count

猜你喜欢

转载自blog.csdn.net/Victordas/article/details/82995558