My super easy AC Java solution one-pass


  • 0
    D

    Use two pointers and dummy node, one pointer goes n steps, then another pointer start to go, until meets the end, delete the pre next node.

    '''
    public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(-1);
    dummy.next = head;
    ListNode cur = dummy;
    ListNode pre = dummy;
    while (n-- > 0) {
    cur = cur.next;
    }
    while (cur.next != null) {
    pre = pre.next;
    cur = cur.next;
    }
    pre.next = pre.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.