My simple Java solution


  • 0
    S
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            
            HashMap<Integer, ListNode> nodes = new HashMap<Integer,ListNode>();
            
            ListNode tmp = head;
            ListNode remove;
            
            int i = 0;
            while (head != null){
                nodes.put(i, head);
                head = head.next;
                i++;
            }
            
            if (i == 1) return null;
            
            if (i - n == 0) {
                tmp = tmp.next;
            } else {
                remove = nodes.get(i - n - 1);
                remove.next = remove.next.next;
            }
            
            return tmp;
            
        }
    }
    

Log in to reply
 

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