19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int len = 0;
        ListNode current = head;
        while(current != null){
            len++;
            current = current.next;
        }
       int required = len - n;
        if(required == 0) return head.next;
        ListNode c = head;
        for(int i =0; i < len; i++){
            if(i == required-1) {
                c.next = c.next.next;
               
            }
             else c = c.next;
        }
        return head;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s