Easy understand Java One Pass solution without dummy head


  • 0
    A

    A simple easy understand solution in Java.

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head;
        ListNode fast = head;
        // Build the gap between fast and slow
        for (int i = 0; i < n; i++) {
            fast = fast.next;
            // When n happens to be the first element in linked list
            if (fast == null) {
                head = head.next;
                return head;
            }
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
    

Log in to reply
 

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