[Linked list] The last k nodes in the linked list

 int length (pHead): find the length of the linked list

Assuming that the length of the linked list is n, finding the k nodes after the reciprocal is to find the linked list with the n-k+1th node as the head node, and only requires n

, and then the pointer takes nk steps from the head node of the linked list

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode FindKthToTail (ListNode pHead, int k) {
        // write code here
        int len=length(pHead);
        if(len<k)return null;
        int n=len-k+1;
        int step=0;
        ListNode p=pHead;
        for(int i=0;i<n-1;i++){
            p=p.next;
        }
        return p;
    }
    public int length(ListNode pHead){
        if(pHead==null)return 0;
        int len=0;
        ListNode p=pHead;
        while(p!=null){
            p=p.next;
            len++;
        }
        return len;
    }
}

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/124412698