题目如下:
解题思路:首先求出链表的长度length,然后令k = k%length,得出的k即为要rotated长度。从头开始遍历链表到第k个元素,将k的next指向none,原链表的尾节点指向头结点即可。
代码如下:
class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if k == 0 or head == None: return head length = 0 node = head tail = None while node != None: if node != None: tail = node length += 1 node = node.next k = k % length if k == 0: return head i = 1 node = head while i + k < length: node = node.next i += 1 newHead = node.next node.next = None tail.next = head return newHead