# [leetcode题解]61. Rotate List(链表旋转)

python代码：

```class Solution(object):
def rotateRight(self, head, k):
"""
:type k: int
:rtype: ListNode
:author: 凌风技术站-iaccepted
"""
if head is None:

#求得链表长度并对k进行一个取余操作
k = k % len

#双指针法求链表中倒数第k个元素的位置
pre = ListNode(-1)
q = pre
while p is not None and k > 0:
p = p.next
k = k - 1

if p is None:

while p is not None:
p = p.next
q = q.next

#将后续的元素使用尾插法一次插入链表前端
p = q.next
q.next = None
q = pre
while p is not None:
t = p.next
p.next = q.next
q.next = p
q = p
p = t
return pre.next

len = 0
while head is not None:
len += 1
return len```

c++代码：

```class Solution {
public:
//本文源：凌风技术站-iaccepted
ListNode* rotateRight(ListNode* head, int k)
{

ListNode *pre = new ListNode(-1);

ListNode *p = head, *q = head;

//求链表的总长度len
int len = 0;
while(p != NULL)
{
++len;
p = p->next;
}

k %= len;

//两个指针的方法去链表中倒数第k个元素
while(k > 0)
{
q = q->next;
--k;
}

if (q == NULL)return head;

while(q->next != NULL)
{
p = p->next;
q = q->next;
}

//将后面的整段插入链表的前端
q->next = pre->next;
pre->next = p->next;
p->next = NULL;
return pre->next;
}
};```