【python/M/61】Rotate List

题目

这里写图片描述

基本思路

  1. 添加头结点
  2. 求链表长度
  3. 处理一下k,k要对长度取余
  4. 画图,想想怎么旋转
  5. 一定注意特殊情况:链表空或者长度为1的,k为0和k为链表长度的。先进行预判,效率比较高

代码

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

class Solution:
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        # 处理空链表和k=0的情况
        if head == None or k == 0:
            return head
        # 添加一个头节点
        dummy = ListNode(0)
        dummy.next = head

        p = head
        # 先求得链表长度
        length = 1
        while p.next:
            p = p.next
            length += 1

        if length == 1 or k%length == 0:
            return head

        k = length - (k % length)

        q = dummy
        for i in range(k):
            q = q.next
        dummy.next = q.next
        q.next = None
        p.next = head

        return dummy.next         

运行结果

231 / 231 test cases passed.
Status: Accepted
Runtime: 52 ms

猜你喜欢

转载自blog.csdn.net/alicelmx/article/details/81189353