Accepted Java Solution using two pointers


  • 1
    V

    public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {

        if(head.next == null){
            return null;
        }
        
        ListNode p = head;
        ListNode q = head;
        
        while(n != 0){
            q = q.next;
            n--;
    
            /*
              if n equals to the number of nodes, that means remove the first node, 
              so just let the head to be the head.next.
             */
            if(q.next == null && n != 0){
                head = head.next;
                return head;
            }
        }
        
        while(q.next != null){
            q = q.next;
            p = p.next;
        }
        
        if(n == 1){
            p.next = null;
            return head;
        }else{
            p.next = p.next.next;
            return head;
        }
    }
    

    }


Log in to reply
 

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