【leetcode】61. 旋转链表 (python)

题目链接:61.旋转链表

在这里插入图片描述
在这里插入图片描述

写法一:暴力

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        # 暴力:每次移动一个,时间复杂度 O(N^2),空间复杂度O(1)
        if not head or not head.next:
            return head
        p, cnt = head, 0
        while p:
            p = p.next
            cnt += 1  # cnt: 链表长度
        if k > cnt:
            k = k % cnt
        h, p = head, head
        while k:
            while p.next:
                pre = p
                p = p.next
            pre.next = None
            p.next = h
            h = p
            k -= 1
        return h

写法二

# 循环右移, 时间复杂度O(n), 空间复杂度O(1)
#  思路:指针遍历到倒数第k个元素,将其后所有元素插入到链表头部。
    # 如何确定倒数第k个位置的元素?
    #    -->遍历两遍链表,第一遍遍历确定链表元素总个数cnt。第二遍遍历到第cnt-k个位置就是倒数第k个元素。
    # 注意:如果 k > len(head): 取余数,相当于移动余数个元素
class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next: # 0或者1个元素,移动多少个位置都还是原样
            return head
        p, cnt = head, 0
        while p:  # 确定链表元素总个数
            p = p.next
            cnt += 1
        k = k % cnt # 取余数,循环右移余数个位置
        if k == 0:  
            return head
        p1 = head
        for i in range(cnt - k): # 寻找倒数第k个位置
            pre1 = p1
            p1 = p1.next
        pre1.next = None # 在倒数第k个位置,断开链表
        hh = p1  # hh 为新链表的头指针
        while p1.next: # 寻找到最后一个元素
            p1 = p1.next
        p1.next = head # 让最后一个元素的指针指向head
        return hh

猜你喜欢

转载自blog.csdn.net/xiaoyue_/article/details/131667528