import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
//先找到倒数第n个节点
ListNode f = head;
ListNode s = head;
while(n>0){
if(f!=null){
f = f.next;
}//此题不用考虑n大于链表长度
n--;
}
ListNode pre = new ListNode(0);
pre.next = s;
if(f==null){
//此时说明删除的是头节点,因为n最多等于链表长度
return head.next;
}
while(f!=null){
f=f.next;
s=s.next;
pre = pre.next;
}
pre.next = s.next;
return head;
}
}



京公网安备 11010502036488号