Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
删除倒数第N个节点。设两个分开n距离的指针 同时前进 当后一个指针指向null时 前一个指针就到要删除的节点啦 然后删除这个节点。(考虑特殊情况 删除头尾节点)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null||head.next==null)
return null;
ListNode l1=head;
ListNode l2=head;
ListNode l3=l1;
while(n>0){
l2=l2.next;
n--;
}
while(l2!=null){
l3=l1;//注意 这里用l3保留l1前一个节点 方便最后节点的删除。也可以用编程之美里面删除任意节点的方法
l1=l1.next;
l2=l2.next;
}
if(l1==head){
head=head.next;
}
if(l1.next==null){
l3.next=null;
}
else{
l3.next=l1.next;
}
return head;
}
}