My java solution, using a fast pointer


  • 0
    1. fast pointer move n steps in advance
    2. cur pointer and fast pointer move together
    3. do the reconnection
    public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head == null) return head;
            
            ListNode fast = head;
            ListNode fake = new ListNode(0);
            fake.next = head;
            while(n > 0){
                if(fast == null)
                    fast = head;
                fast = fast.next;
                n --;
            }
            ListNode cur = fake;
            while(fast != null){
                fast = fast.next;
                cur = cur.next;
            }
            cur.next = cur.next.next;
            return fake.next;
        }
    

Log in to reply
 

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