"Prove safety offer" reciprocal interview questions 15 list of the k-th node Java version

Method book: traversing a node k is obtained by the penultimate two nodes. Note that the first node is empty, k <= 0, k is larger than the number of nodes.

    public ListNode find(ListNode head, int k){
        if(head == null || k <=0){
            return null;
        }
        ListNode first = head, second = head;
        for(int i=1; i<=k; i++){
            //如果k超出了节点的个数
            if(first == null){
                return null;
            }else{
                first = first.next;
            }
        }
        
        while(first != null){
            first = first.next;
            second = second.next;
        }
        return second;
    }

Guess you like

Origin www.cnblogs.com/czjk/p/11611754.html