题目链接:Leetcode 61. Rotate List

本题采用快慢指针的思路,让fast指针比slow指针多走k步,当fast走到链表最后一个结点时,断开slow指针所在位置,使其指向None;并将fast指针指向链表头结点。

考虑到k值可能大于链表长度,需将k值在链表长度上进行取模运算。

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head: return head # base case

fast, slow, l = head, head, head
n = 0
while l:
n += 1
l = l.next
k %= n # 取模

if k == 0: return head # 若k取模后等于0,那是否旋转链表并无差别,直接返回链表本身

while k:
fast = fast.next
k -= 1
while fast.next:
slow, fast = slow.next, fast.next
new_head = slow.next
slow.next = None
fast.next = head
return new_head