My java solution using list-O(n) 237 ms


  • 0
    C
    public ListNode removeNthFromEnd(ListNode head, int n) {
    	List<ListNode> lns = new ArrayList<ListNode>(); 
    	ListNode node = head;
    	while(lns.add(node)&&node.next!=null){
    		node=node.next;
    	}
    	int size = lns.size();
    	if(n==0||n>size){
    		return lns.get(0);
    	}else if(n!=0&&n<size){
    		ListNode removeNode = lns.get(size-n);
    		ListNode removeNodePev = lns.get(size-n-1);
    		removeNodePev.next=removeNode.next;
    	}else{//if is the head node
    		lns.remove(0);
    	}
    	
    	return size>0?lns.get(0):null;
    }

Log in to reply
 

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