Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
- 需要一个dummy node,dummy位置是0,prev在dummy
- 先让head走 从1 开始i <= n,跳出循环head在n+1上,head和prev相隔n个
- 同时走,head到null的时候,prev正好在要删除的node的前一个
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i = 1; i <= n; i++ ){
head = head.next;
}
while (head != null){
head = head.next;
pre = pre.next;
}
pre.next = pre.next.next;
return dummy.next;
}
}