给定一个链表,旋转链表,将链表每个节点向右移动 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 == NULL || !k) return head;
ListNode* circleNode = head;
int len = 1;
while(circleNode->next){
circleNode = circleNode->next;
len++;
}
if(len == 1) return head;
circleNode->next = head;
circleNode = circleNode->next;
k = len - k%len;
while(k--){
circleNode = circleNode->next;
}
ListNode* ansNode = circleNode;
len--;
while(len--){
circleNode = circleNode->next;
}
circleNode->next = NULL;
return ansNode;
}
};