思路:这道题主要是边界条件的考虑,如果删除的是第1个元素的时候,要考虑到
哑结点的使用
/**
* 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 p2 = head;
while(p2 != null && n > 0){
p2 = p2.next;
n--;
}
ListNode p1 = new ListNode(0);
p1.next = head;
head = p1;
while(p2 != null){
p1 = p1.next;
p2 = p2.next;
}
p1.next = p1.next.next;
return head.next;
}
}
来源:CSDN
作者:fsdgfsf
链接:https://blog.csdn.net/fsdgfsf/article/details/104282346