https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
public class Solution {
public static void main(String[] args) {
Solution solution=new Solution();
ListNode h5=new ListNode(5);
ListNode h4=new ListNode(4,h5);
ListNode h3=new ListNode(3,h4);
ListNode h2=new ListNode(2,h3);
ListNode h=new ListNode(1,h2);
ListNode hh= solution.removeNthFromEnd(h,2);
while(hh!=null) {
System.out.print(hh.val);
hh=hh.next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head;
ListNode slow = head;
//慢指针比快指针慢N步,那么快指针指向末尾的null时,慢指针刚好指向要删除结点的前驱结点
while (fast.next != null) {
fast = fast.next;
if (n == 0) {
slow = slow.next;
} else {
n--;
}
}
if (n != 0) { //没追上,说明删除的是头指针
return head.next;
} else {
slow.next = slow.next.next;
}
return head;
}
public static class ListNode {
int val;
ListNode next;
ListNode() { }
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}