"The last k nodes in the BM8 linked list" JavaScript implementation

topic description

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

Data range: 0≤n≤10^5, 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)

Example 1:

Input: {1,2,3,4,5},2 Output: {4,5}

Example 2:

Input: {2},8 Output: {}

answer:

method one:

function FindKthToTail( pHead ,  k ) {
    var cur = pHead;
    var length = 0;
    while(cur) {
        length++;
        cur = cur.next;
    }
    if (length <k) return null;
    cur = pHead;
    for (var i =0; i < length-k; i++) {
        cur = cur.next;
    }
    return cur;
}

Method Two:

The fast pointer moves fast for k steps. When the fast pointer is empty, the full pointer points to the kth node from the bottom

function FindKthToTail( pHead ,  k ) {
    let fast = pHead, slow = pHead;
    for(var i = 0; i < k; i++) {
        if(fast == null) return null;
        fast = fast.next;
    }
    while(fast){
        fast = fast.next;
        slow = slow.next;
    }
    return slow;
}

Guess you like

Origin blog.csdn.net/qq_42101569/article/details/126202747