LinkedList With Two Ptr

Remove Nth Node from End of List

How to analyze? assume n = 2

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8

s f s f

remove nth from List.

keep slow and fast n steps away.

when fast reach end, slow is the node need to be deleted.

what do we need to keep for deleted s ? (prev s)

prev = s.next;

Corner case :

1) prev = null ?

which means s didn't move, head is the one need to be removed. simply return s.next;

2) f = null ?

whole list size < n, no need to remove.

public ListNode removeNthFromTail(ListNode head, int n) {
        if (n == 0) {
            return head;    
        }
        ListNode anchor = head;
        ListNode s = head;
        ListNode f = move(head,n);
        ListNode ps = null;
        while(f.next != null) {
            ps = s;
            s = s.next;
            f = f.next;
        }
        if (ps == null) {
            return s.next;
        }
        ps.next = s.next;
        return head;
}

ListNode move(ListNode head, int n) {
       while(n > 0) {
            head = head.next;
            n--;
       }
       return head;
}

results matching ""

    No results matching ""