Simple 6-line Java one-pass solution


  • 8
    D

    public class Solution {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode start=new ListNode(0),slow=start,fast=start;
        start.next=head;
        for(int i=0;i<n;i++) fast=fast.next;
        while(fast.next!=null) {fast=fast.next;slow=slow.next;}
        slow.next=slow.next.next;
        return start.next;
    }
    

    }


  • 0
    B

    Nice job creating a new list node at the beginning to use as a placeholder.


  • 0
    C

    i don't understand it.why it's i < n, not i < len-n.


  • 0
    P

    The basic idea is the fast pointer is n nodes ahead of slow pointer. So when fast.next is null, slow is in the right position that its next node can be removed by statement slow.next = slow.next.next;.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.