题目描述
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.
解题思路
先遍历一遍确定链表中元素的个数n,然后k对n求模,因为移动n的倍数还是链表本身。 然后找到倒数第k个,这个就是移动之后的新的链表头。
AC代码
class Solution {
public:
ListNode* rotateRight(ListNode* head,
int k) {
if (head == NULL)
return head;
int n =
1;
ListNode *tail = head;
while (tail->next != NULL) {
n +=
1;
tail = tail->next;
}
k = k % n;
if (k ==
0)
return head;
tail->next = head;
for (
int i =
1; i < n- k; ++i) {
head = head->next;
}
ListNode* ans = head->next;
head->next = NULL;
return ans;
}
};
转载请注明原文地址: https://ju.6miu.com/read-14211.html