61.旋转链表

难度:中等
题目描述:
61.旋转链表_第1张图片
思路总结:思路呢,很简单,无非就两点,连环,双指针。最后需要求余n,以防k>>n的情况
题解一:
个人版-超时,改进几行代码后,AC。

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

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        #思路:先将链表变成循环链表,然后在进行切割。
        if not head:return head
        cur = head
        n = 1
        while cur.next:
            cur = cur.next
            n += 1
        tail = cur
        cur.next = head
        fast = head
        for i in range(k%n):
            fast = fast.next
        while fast != cur:
            fast =fast.next
            head = head.next
        res = head.next
        head.next = None
        return res

题解一结果:
在这里插入图片描述

你可能感兴趣的:(朱滕威的面试之路)