题解 | #调整牛群顺序#
调整牛群顺序
https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode moveNthToEnd (ListNode head, int n) {
// write code here
if(head==null||head.next==null)return head;
if(n==1)return head;
ListNode pre=head;
ListNode end=head;
ListNode temp=head;
int size=1,index=0;
while(end.next!=null){
size++;
end=end.next;
}
if(n==size){
head=head.next;
temp.next=null;
end.next=temp;
return head;
}
while(pre.next.next!=null){
index++;
if(index==size-n)
{
temp=pre.next;
pre.next=pre.next.next;
temp.next=null;
end.next=temp;
return head;
}
pre=pre.next;
}
return head;
}
}

查看12道真题和解析