Monday, February 5, 2018

[2018-Interview] Remove Nth Node From End of List

Original question: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

My answer:

Have a endNode move forward so that it is n step further than currentNode, then move endNode until last one. The next of currentNode is then the one to be deleted.



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n < 1 || head == null) {
            return null;
        }
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode prevNode = preHead;
        ListNode currentNode = head;
        ListNode endNode = head;
        int step = 0;
        while (endNode.next != null && step < n) {
            endNode = endNode.next;
            step++;
        }
        if (step < n) {
            return preHead.next.next;
        }
        while (endNode.next != null) {
            currentNode = currentNode.next;
            endNode = endNode.next;
        }
        currentNode.next = currentNode.next.next;
        return preHead.next;
    }
}

No comments:

Post a Comment