leetcode25 K个一组反转链表(python3)

leetcode25 K个一组反转链表

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

示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5


直接上代码:
**第一种:**
# 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
        """
        hd = ListNode(0)
        hd.next = head

        def reverse(start, k):
            n = k
            tail = start.next

            while tail is not None and n > 1:
                tail = tail.next
                n -= 1

            if tail is None:
                return hd.next

            _head = start
            tmpPtr = _head.next
            for i in range(k - 1):
                p = _head.next
                _head.next = p.next
                p.next = tail.next
                tail.next = p

            return reverse(tmpPtr, k)

        a = reverse(hd, k)
        return a

第二种:

# 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
        """
        hd = ListNode(0)
        hd.next = head

        def reverse(start, k):
            n = k
            tail = start.next

            while tail is not None and n > 1:
                tail = tail.next
                n -= 1

            if tail is None:
                return 

            _head = start
            tmpPtr = _head.next
            for i in range(k - 1):
                p = _head.next
                _head.next = p.next
                p.next = tail.next
                tail.next = p

            reverse(tmpPtr, k)

        return hd.next

两种方法思路是一样的,都是先选取一个k的长度,比如:1234,将tail定义为4,然后每次讲第一个数据插入4的后面,就是分别为:2341,3421,4321,实现了反转。

区别:第一种方法,主函数中有return值,所以在递归的时候也要return回去,那么最后return的时候才会有值返回。第二种方法:主函数中的return只是将函数停止,没有返回值,那么递归的时候也不用return,函数整体是将链表按照规则反转,而在最后的时候return了hd.next头文件到函数外部就行。

猜你喜欢

转载自blog.csdn.net/weixin_43944749/article/details/85109970