思想:利用三根指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pi = head;
ListNode pj = head;
ListNode pk = head;
for(int i=0;i<n;i++) {
pk = pk.next;
}
while(pk!=null) {
pk = pk.next;
if(pj!=head) {
pi = pi.next;
}
pj = pj.next;
}
if(pi==pj) {
return head.next;
}
pi.next = pj.next;
return head;
}
}