题解 | #调整牛群顺序#
调整牛群顺序
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) {
if(n==1) return head;
ListNode phead=new ListNode(-1);
phead.next=head;
ListNode s=phead;
ListNode f=phead;
for(int i=0;i<n;i++) f=f.next;
while(f.next!=null){
s=s.next;
f=f.next;
}
ListNode t=s.next;
s.next=s.next.next;
t.next=null;
f.next=t;
return phead.next;
// write code here
}
}
快慢指针逻辑很简单,关键是两个特例,第一个和倒数第一。
广发银行公司氛围 23人发布