题目
Number: 61
Difficulty: Medium
Tags: Linked List, Two Pointers
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
题解
反转倒数第k个结点开头的链表。
代码
ListNode* rotateRight(ListNode* head, int k) {
if(!head || !k || !head->next){
return head;
}
int n = 1;
ListNode *p = head;
while(p->next){
p = p->next;
n++;
}
k %= n;
n -= k;
p->next = head;
if(k){
while(n--){
p = p->next;
}
}
head = p->next;
p->next = NULL;
return head;
}