My Java solution w/ fast & slow pointers


  • 0
    S
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode ptr1 = head;
            ListNode ptr2 = head;
            for (int i = 0; i < n; i ++){
                if (ptr2.next == null){ /*if removing the head node*/
                    return head.next;
                }
                ptr2 = ptr2.next;
            }       
            while (ptr2.next != null){
                ptr1 = ptr1.next;
                ptr2 = ptr2.next;
            }       
            ptr1.next = ptr1.next.next;
            return head;
        }
    }
    

Log in to reply
 

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