文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Rotate List2. Solution
/**
* 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;
}
int n = 0;
ListNode* pre = nullptr;
ListNode* current = head;
while(current) {
n++;
pre = current;
current = current->next;
}
pre->next = head;
int target = n - k % n;
current = head;
while(target) {
target--;
pre = current;
current = current->next;
}
pre->next = nullptr;
return current;
}
};
网友评论