题目描述:给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
解题思路:先遍历链表长度,然后将末尾节点指向头节点,计算出k的值。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head||!head->next||k==0) return head;
int len=1;
ListNode*cur=head;
while(cur->next&&++len) cur=cur->next;
cur->next=head;
k=len - k%len;
while(k--) cur=cur->next;
head=cur->next;
cur->next=nullptr;
return head;
}
};