就是将倒数的几个数放到前面,再把前面的数放到后面去接起来。代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return head
length = 0
head1 = head
while head1.next:
length += 1
head1 = head1.next
length = length + 1
k = k % length
head2 = head
head1.next = head2
for i in range(length - k):
if i == length - k - 1:
head =head.next
head2.next = None
else:
head2 = head2.next
head = head.next
return head