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 快指针走到尾节点时 慢指针刚好到要删除的点
/**
* 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;
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;
}
}