DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Remove Nth node from the end of the LinkedList

Remove Nth node from the end of the linkedlist

/**
 * 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) {
        ListNode first = head;
        ListNode sec = head;
        while(n-->0){
            first = first.next;
        }
        if(first ==null) return head.next;
        ListNode temp  = sec;
        while(first!=null){
            first = first.next;
            temp  = sec;
            sec = sec.next;
        }
        temp.next = sec == null ? null : sec.next;
        return head;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)