My O(n)time O(1) space java solution


  • 0

    1: we need to create a dummy node when the head of a list is not sure.
    2: use fast point check if the current node is the end of the list.

    
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head == null){
                return null;
            }
            ListNode dumynode = new ListNode(0);
            dumynode.next = head;
            
            ListNode fast = dumynode;
            ListNode slow = dumynode;
            while(n > 0 && fast.next != null){
                fast = fast.next;
                n--;
            }
            while( fast.next != null){
                slow = slow.next;
                fast = fast.next;
            }
            if( slow.next != null){
                slow.next = slow.next.next;
            }
            return dumynode.next;
        }
    

Log in to reply
 

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