用到了双指针
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
//想法:双指针
ListNode fast = head;
ListNode slow = head;
ListNode test =head;
ListNode newHead = slow;
int len = 0;
//先遍历链表长度,预防n=len而产生的空指针
while(test != null){
len++;
test = test.next;
}
if(n == len) return head.next;
//fast先遍历n个节点
for(int i=0;i<n;i++) fast =fast.next;
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return newHead;
}
}