def remove_nth_from_end(head,n):
dummy=type('N',(),{'val':0,'next':head})()
fast=slow=dummy
for _ in range(n+1): fast=fast.next
while fast: slow=slow.next; fast=fast.next
slow.next=slow.next.next
return dummy.next
public ListNode removeNthFromEnd(ListNode head,int n){
ListNode dummy=new ListNode(0); dummy.next=head;
ListNode fast=dummy,slow=dummy;
for(int i=0;i<=n;i++) fast=fast.next;
while(fast!=null){slow=slow.next;fast=fast.next;}
slow.next=slow.next.next;
return dummy.next;
}
n+1 gap technique. range(n+1) vs i<=n.
def remove_nth_from_end(head,n):
dummy=type('N',(),{'val':0,'next':head})()
fast=slow=dummy
for _ in range(n+1): fast=fast.next
while fast: slow=slow.next; fast=fast.next
slow.next=slow.next.next
return dummy.next
public ListNode removeNthFromEnd(ListNode head,int n){
ListNode dummy=new ListNode(0); dummy.next=head;
ListNode fast=dummy,slow=dummy;
for(int i=0;i<=n;i++) fast=fast.next;
while(fast!=null){slow=slow.next;fast=fast.next;}
slow.next=slow.next.next;
return dummy.next;
}
1. Create gap of n+1 2. Move both until fast null 3. Remove slow.next