My Java solution using Hash Map (one pass over the list)


  • 1
    Y
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head==null || head.next == null)
                return null;
            HashMap <Integer, ListNode> map = new HashMap<>();
            int length=0;
            ListNode temp = head;
            while (temp != null) {
                length++;
                map.put(length, temp);
                temp = temp.next;
            }
            temp = map.get(length-n+1);
            if (temp == head)
                head = head.next;
            else if (n == 1)
                map.get(length-1).next = null;
            else map.get(length-n).next = temp.next;
            return head;
        }
    }

Log in to reply
 

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