思路
先统计链表的长度n
,如果k>n
,就取k=k%n
,如果k==0
,就不用做变化,否则找到新链表头head2
和它的前驱节点pre
,将链表重新断开并连接,返回新链表头即可。
代码
/**
* 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 || head->next == NULL)
return head;
ListNode* tail = head;
int n = 1;
while (tail->next) {
n++;
tail = tail->next;
}
if (k >= n)
k = k % n;
if (k == 0)
return head;
int time = n - k - 1;
ListNode* pre = head;
while(time--) {
pre = pre->next;
}
ListNode* head2 = pre->next;
tail->next = head;
pre->next = NULL;
return head2;
}
};