题解 | #调整牛群顺序#
调整牛群顺序
https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
struct ListNode* moveNthToEnd(struct ListNode* head, int n ) {
// write code here
int num = 0;
struct ListNode* p = head;
if(n == 1) return head;
while(p != NULL){
p =p->next;
num++;
}
p = head;
struct ListNode* q;
if(n == num){
q = head;
head = head->next;
p = p->next;
}
else{
int i;
for(i=1;i<num-n;i++){
p = p->next;
}
q=p->next;
p->next = q->next;
}
q->next = NULL;
while(p->next != NULL){
p = p->next;
}
p->next = q;
return head;
}