package interviewquestions.easy;

import interviewquestions.utils.ListNode;

/**
 * Created by sherxon on 1/4/17.
 */
public class RemoveNthNodeFromEndofList {
    public ListNode removeNthFromEnd(ListNode h, int nu) {
        int size=0;
        ListNode head=h;
        while(head!=null){
            head=head.next;
            size++;
        }
        int i=0;
        ListNode n=h;
        ListNode p=h;
        while(i<size-nu){
            i++;
            p=n;
            n=n.next;
        }
        if(i==0){
            if(p.next==null)return null;
            else h=p.next;
        }
        p.next=n.next;
        return h;

    }
}

@@ -153,16 +153,17 @@
 fList %7B%0A
+%0A
     publ
@@ -634,16 +634,1004 @@
 urn h;%0A%0A
+    %7D%0A%0A%0A    public ListNode removeNthFromEnd(ListNode h, int nu) %7B%0A        int size = 0;%0A        ListNode head = h;%0A        while (head != null) %7B%0A            head = head.next;%0A            size++;%0A        %7D%0A        int i = 0;%0A        ListNode n = h;%0A        ListNode p = h;%0A        while (i %3C size - nu) %7B%0A            i++;%0A            p = n;%0A            n = n.next;%0A        %7D%0A        if (i == 0) %7B%0A            if (p.next == null) return null;%0A            else h = p.next;%0A        %7D%0A        p.next = n.next;%0A        return h;%0A%0A    %7D%0A%0A    /**%0A     * This is the recursive approach%0A     */%0A%0A    int n = 0;%0A%0A    public ListNode removeNthFromEndR(ListNode head, int n) %7B%0A        if (head == null %7C%7C head.next == null) return null;%0A%0A        this.n = n;%0A        remove(head);%0A        return this.n == 0 ? head.next : head;%0A    %7D%0A%0A    void remove(ListNode x) %7B%0A        if (x == null) return;%0A        remove(x.next);%0A        if (n == 0) %7B%0A            x.next = x.next.next;%0A        %7D%0A        n--;%0A%0A
     %7D%0A%7D%0A

remove end of list recursive approach