Why my solution can not get pass in certain case like this?


  • 0
    S
    public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        int i = 0;
        ListNode start = new ListNode(1);
        start.next=head;
        ListNode list = start;
        int len = length(list);
        int t = len-n-1;
        
        while(list!=null){
        	if(list.next==null) break;
        	if(i==t){
        		list.next=list.next.next;
        	}
        	else{
            	list=list.next;
            	i++;
        	}
        }
        return head;
    }
    private int length(ListNode node){
    	int len=0;
    	while(node!=null){
    		node=node.next;
    		len++;
    	}
    	return len;
    }
    

    }

    Test Case: {1}, 1 expected {} output {1}


  • 1
    S

    You should return start.next


  • 0
    S

    When I return start.next, it still gives me the error:
    Input: {1,2}, 2
    Output: {}
    Expected:{2}


  • 0
    S

    But It got accepted when I return start.next in the first if block. Thank you!


  • 0
    S

    The reason Input: {1,2}, 2 Output: {} Expected:{2} is that you should put

    i++;

    outside if-else statement. Think about it. Once if(i==t) holds, it will keeping running

    list.next=list.next.next;


  • 0
    S

    Thank you very much! Your suggestion is very clever and useful


Log in to reply
 

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