61. 旋转链表
为保证权益,题目请参考 61. 旋转链表(From LeetCode).
解决方案1
Python
python
# 61. 旋转链表
# https://leetcode-cn.com/problems/rotate-list/
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def rotateRight(self, head, k: int):
if head is None:
return None
tail = head
count = 1
while tail.next is not None:
tail = tail.next
count += 1
k = k % count
k = count - k
if k == 0:
return head
mid = head
k -= 1
while k != 0:
k -= 1
mid = mid.next
tail.next = head
head = mid.next
mid.next = None
return head
if __name__ == "__main__":
solution = Solution()
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
34
35
36
37
38
39
40
41
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
34
35
36
37
38
39
40
41