美文网首页
python实现leetcode之61. 旋转链表

python实现leetcode之61. 旋转链表

作者: 深圳都这么冷 | 来源:发表于2021-09-04 21:19 被阅读0次

    解题思路

    快慢指针

    1. 快指针先走k步
    2. 快慢指针一起走知道快指针到尾部,慢指针就是新的头
    3. 将老的尾接新的头,就是ans

    61. 旋转链表

    代码

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def rotateRight(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if not head: return head
            length = len_of_chain(head)
            k %= length
            if not k: return head
            fast = head
            while k:
                fast = fast.next
                k -= 1
            p1 = ans = head
            p2 = fast
            while fast:
                p1 = ans
                ans = ans.next
                p2 = fast
                fast = fast.next
            p1.next = None
            p2.next = head
            return ans
    
    
    def len_of_chain(head):
        if not head: return 0
        return 1 + len_of_chain(head.next)
    
    效果图

    相关文章

      网友评论

          本文标题:python实现leetcode之61. 旋转链表

          本文链接:https://www.haomeiwen.com/subject/fthdwltx.html