On Time(pass twice times but not once) My Solution


  • 0
    L

    the main idea is find the positive order you want to remove,how can find it? you can use fast step to get the totalNum,
    and then you just need to remove the 'nth' num and delete it;

    class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
    val = x;
    next = null;
    }
    }

    public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode fast=head;

    	ListNode node=head;    	
    	
    	int count=1;
    	
    	while(fast!=null && fast.next!=null){
    	  
    	  fast=fast.next.next; 
    

    //i'm silly so i think there is two situation that total num is odd or even but actally i get the total num
    if(fast==null){
    count+=1;
    }else{
    count+=2;
    }
    }
    //get the nth to delete
    int toDeleteIndex=count-n+1;

         if(toDeleteIndex==1){
        	 head=head.next;
        	 return head;
         }
         
         for(int i=1;i<toDeleteIndex-1;i++){
        	 node=node.next;
          }
         
         node.next=node.next.next;
         
         
    	return head;
    	     
    }
    

    }


Log in to reply
 

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