Niuke Top101 JS implementation to get the last k nodes in the linked list

describe

Input a linked list with a length of n, set the value of the element in the linked list to ai, and return the last kth node in the linked list.

If the length of the linked list is less than k, return a linked list of length 0.

  

Data range: 0 ≤ n ≤ 10^50≤n≤105, 0 ≤ ai ≤ 10^9, 0 ≤ k ≤ 10^9

Requirements: space complexity O(n), time complexity O(n)

Advanced: space complexity O(1), time complexity O(n)

For example, when {1,2,3,4,5},2 is input, the corresponding linked list structure is shown in the figure below:

 

Among them, the blue part is the last two nodes of the linked list, so just return the second last node (that is, the node with a node value of 4), and the system will print all the subsequent nodes for comparison.

Example 1

enter:

{1,2,3,4,5},2

return value:

{4,5}

illustrate:

Return the penultimate node 4, and the system will print all subsequent nodes for comparison.

Example 2

enter:

{2},8

return value:

{}

Idea: First of all, you need to judge whether k is greater than the length of the linked list, so you must first traverse to get the length of the linked list, and then judge directly. If it is greater than the length of the linked list, return null, and then you need to judge whether k is equal to 0, because There is no penultimate 0th element, so if k is equal to 0, it will return null, and in another case, it will return null if the linked list is empty. The follow-up logic is very simple, which is to judge whether the linked list has reached the number, and return directly when it reaches the number. The complete code is as follows:

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pHead ListNode类 
 * @param k int整型 
 * @return ListNode类
 */
function FindKthToTail( pHead ,  k ) {
    // write code here
    let n=0;
    let n1=0;
    let p1=pHead;
    while(p1) {
        n++;
        p1=p1.next;
    }
    if(k>n||k===0||pHead===null) {
        return null;
    }
    else {
        while(pHead) {
            n1++;
            if(n1===n-k+1) {
                return pHead;
            }
            else {
                pHead=pHead.next;
            }
            
        }
    }
}
module.exports = {
    FindKthToTail : FindKthToTail
};

Guess you like

Origin blog.csdn.net/qq_43781887/article/details/128197475