题解 | #调整牛群顺序#
调整牛群顺序
https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* moveNthToEnd(ListNode* head, int n) {
// write code here
if(!head || !head->next){
return head;
}
int N = 0;
auto *cur = head;
ListNode *end;
while(cur !=nullptr){
N ++;
if(cur->next == nullptr)
end = cur;
cur = cur->next;
}
cur = head;
ListNode * pre = nullptr;
int target_index = N - n + 1;
int index = 0;
while(cur != nullptr){
index ++;
if(index == target_index){
if(pre == nullptr){
head = cur -> next;
cur->next = nullptr;
end->next = cur;
}else if(cur == end){
break;
}else{
pre->next = cur->next;
cur->next = nullptr;
end->next = cur;
}
break;
}
pre = cur;
cur = cur->next;
}
return head;
}
};
查看16道真题和解析