remove-nth-node-from-end-of-list

LeetCode link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/684704570/

Java Solution

/**
 * 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;
        
        //null list
        if (head == null) {
            return head;
        }
        
        for (int i = 0; i < n; i++) {
            if (first.next == null) {
                return (i == n - 1) ? head.next : head;
            }
            first = first.next;
        }
        ListNode second = head;
        while (first.next != null) {
            first = first.next;
            second = second.next;
        }
        
        second.next = second.next.next;
        return head;
    }
}

About Hieu Nguyen

I am a Senior member of technical staff (Oracle, eBay, Microsoft) and a founder of iNest, LLC (an IoT company)
This entry was posted in singly-linked list. Bookmark the permalink.