题目描述:Given a linked list, rotate the list to the right by k places, where k is non-negative.
解析:这条题目用了把单向链表变成环的方法,有趣!
/**
* 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){
return head;
}
ListNode *new_head, *tail;
new_head = tail = head;
int len = 1;
while(tail->next != NULL){
tail = tail->next;
len++;
}
tail->next = head;
k %= len;
for(int i = 0; i < len - k; i++){
tail = tail->next;
}
new_head = tail->next;
tail->next = NULL;
return new_head;
}
};