Come on! Simple Java solution, Only one pass.


  • 0
    M

    To be hoest, we couldn't solve the problem in one pass, if we did not change the structure. so follow the idea, I attach my code below.

    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            
    	Map<Integer,ListNode> nodes = new HashMap<Integer,ListNode>();
    
    	ListNode search = head;
    	int deep = 0;
    	nodes.put(deep,search);
    	while(search.next != null){
    		nodes.put(deep,search);
    		deep++;
    		search = search.next;
    	}
    	
    	int delNumber = deep - n + 1;
    	if(delNumber == 0 ) return head.next;
    	else{
    		ListNode lastNode = nodes.get(delNumber - 1);
    		lastNode.next = lastNode.next.next;
    	}
    	return head;
    	
        }
    }
    

Log in to reply
 

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