My Simple Java Solution with 2 ListNode variables


  • 1
    R
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode tail = head;
        head = dummy;
        
        while (n-- > 0 && tail != null) {
            tail = tail.next;
        }
        
        while (tail != null) {
            tail = tail.next;
            head = head.next;
        }
        
        head.next = head.next.next;
        
        return dummy.next;
        
    }

Log in to reply
 

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