思路是这样:
两个指针,都从头开始,指针A先移动n步,指针B 再开始移动,当A移动到了最后一个节点(next==null),此时B指针正好指的是倒数第n个的前一个。
特殊情况:
1.链表只有头指针且n=1,说明删除头指针
2.倒数第N个正好是头指针(此时A移动n步之后,==null),那直接返回第二个节点作为头。
/**
* 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) {
if(head.next==null&&n==1){
return null;
}
ListNode cur=head;
ListNode target=head;
while(n-->0){
cur=cur.next;
}
if(cur==null){
return head.next;
}
while(cur.next!=null){
cur=cur.next;
target=target.next;
}
target.next=target.next.next;
return head;
}
}