Java with counter, one pass


  • 0
    Y
    public ListNode removeNthFromEnd(ListNode head, int n) {
            int counter=0;
            ListNode tmp;
            ListNode sentinel = new ListNode(0);
            sentinel.next = head;
            tmp = sentinel;
            while(head != null)
            {
                head = head.next;
                counter++;
                if(counter>= n && head != null)
                    tmp = tmp.next;
            }
            tmp.next = tmp.next.next;
            return sentinel.next;
        }
    

Log in to reply
 

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