yxc题解 借鉴方法(常用!)
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head) return head;
int n = 0;
for (auto p = head; p; p = p->next) n ++;
k %= n;
if (!k) return head;
auto tail = head;
while (tail->next) tail = tail->next;
auto p = head;
for (int i = 1; i <= n - k - 1; i ++) p = p->next;
tail->next = head;
head = p->next;
p->next = NULL;
return head;
}
};
这样写也可以
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head) return head;
int n = 0;
auto tail = head;
for (; tail->next; tail = tail->next) n ++; // 这里是tail->next!=NULL,因为tail = tail->next会执行使最终tail指向链表最后一个节点
n++;
k %= n;
if (!k) return head;
// auto tail = head;
// while (tail->next) tail = tail->next;
auto p = head;
for (int i = 1; i <= n - k - 1; i ++)
p = p->next;
tail->next = head; //但是将这行放在n++下面就不行了
head = p->next;
p->next = NULL;
return head;
}
};
另一种写法:(借鉴y总题解写法)
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head) return head;
int n = 0;
for (auto p = head; p; p = p->next) n ++;
auto first = head, second = head;
k %= n;
if (!k) return head;
for (int i = 1; i <= k; i ++)
first = first->next;
int t = n - k - 1;
while (t --) {
first = first->next;
second = second->next;
}
first->next = head;
head = second->next;
second->next = 0;
return head;
}
};