Wins the offer-8: linked list of nodes penultimate k

Turn: https://blog.csdn.net/yjw123456/article/details/81061541

First, the problem-solving ideas

Two pointers p1, p2, start point to the first node p2 let go * k * Then step p1, p2 * go down at the same time when the null point p2, p1 is the penultimate node k

Second, the code

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null){
            return null;
        }
        ListNode p1 = head,p2 = head;
        while(k > 0 & p2 != null){
            p2 = p2.next;
            k--;
        } 
        // P2 DESCRIPTION head point k <= 0, p2 == null && k> 0 . K exceeds the length of the list 
        IF (== head || P2 (P2 == null && k> 0 )) {
             return  null ; 
        } 
        the while (P2 =! null ) { 
            P1 = p1.next; 
            P2 = p2.next; 
        } 
        return P1; 
    } 
}

 

Guess you like

Origin www.cnblogs.com/JimShi/p/11401219.html