Java remove nth node from end of list solution


  • 3
    V

    public class Solution {

    public ListNode removeNthFromEnd(ListNode head, int n) {
    
        if(head == null){
            return head;
        }
        
        ListNode dummy = new ListNode(1);
        ListNode i = dummy;
        ListNode j = dummy;
        dummy.next = head;
        int count = 0;
        
        while(count != n){
            j = j.next;
            count++;
        }
        
        while(j.next != null){
            i = i.next;
            j = j.next;
        }
        
        i.next = i.next.next;
        
        return dummy.next;
    }
    

    }


  • 2
    H

    but two pointers pass the list twice


  • 0
    C

    IMHO, it is one pass. The complexity is n instead of 2n.


  • 0

    In the worst case (n=1) it's 2n. "i = i.next; j = j.next;" will pass the list twice.


Log in to reply
 

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