JAVA, 1ms with comments


  • 0
    S

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode removeNthFromEnd(ListNode node, int n) {

       if(node == null) return node;
       
       ListNode findingDeadEnd = node;  // this node will provide information of the node to be deleted w.r.t the tail
       for(int i = 0; i <n; i++)
       {
           findingDeadEnd = findingDeadEnd.next;
       }
       if(findingDeadEnd == null  )     // if the 1st element had to be deleted
       {
           node=node.next;
       }
       else if(findingDeadEnd.next == null) // any element, except first, to be deleted
       {
           node.next = node.next.next;
           
       }
       else{
           removeNthFromEnd(node.next, n);
       }
       return node;
      

      }
      }


Log in to reply
 

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