Simple one pass solution in java


  • 1
    Y
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) return head;
        ListNode point1 = head;
        ListNode point2 = head;
        int distance = 0;
        while(point1.next!=null){
            if(distance==n){
                point2=point2.next;
                point1=point1.next;
            }
            if(distance<n){
                point1=point1.next;
                distance++;
            }
        }
        if(distance<n)
            return head.next;
        point2.next=point2.next.next;
        return head;
    }

Log in to reply
 

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