DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #19. Remove nth Node from End of List

Space Complexity: O(1)

Time Complexity: O(n)

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || head.next == null) {
            return null;
        }

        ListNode dummy = new ListNode();
        dummy.next = head;

        ListNode slow = dummy;
        ListNode fast = dummy;

        // advance fast node till the nth node
        for (int i = 0; i <= n; i++) {
            fast = fast.next;
        }

        // advance both nodes till fast != null
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }

        // slow now is at the node before the node that has to be deleted
        // bypass the nth node that be to be deleted
        // so we just do not reference that node anymore
        slow.next = slow.next.next;

        return dummy.next;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)