My one pass solution by calculcating the remaining nodes


  • 0
    J
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode dummyHead = new ListNode(-1);
            dummyHead.next = head;
            calculateLenAndRemove(dummyHead, n);
            return dummyHead.next;
        }
        
        private int calculateLenAndRemove(ListNode node, int n)
        {
            if (node == null)
                return 0;
            
            int remainingLength = calculateLenAndRemove(node.next, n);
            if (remainingLength == n)
                node.next = node.next.next;
            
            return remainingLength + 1;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.