How to find nth element from the end of a singly linked list?

后端 未结 28 1147
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 06:45

    Nobody here noticed that Jonathan's version will throw a NullPinterException if the n is larger that the length of LinkedList. Here is my version:

    public Node nth(int n){
            if(head == null || n < 1) return null;
    
            Node n1 = head;
            Node n2 = head;
            for(int i = 1; i < n; i++){
                if(n1.next == null) return null; 
                n1 = n1.next;
            }
    
            while (n1.next != null){
                n1 = n1.next;
                n2 = n2.next;
            }
            return n2;
    }
    

    I just make little change here: when node n1 step forward, instead of checking if n1 is null, I check weather n1.next is null, or else in while loop n1.next will throw a NullPinterException.

提交回复
热议问题