leetcode-day19-返回倒数第 k 个节点[面试题 0

2020-11-05  本文已影响0人  孙静静
image.png

双指针法

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {number}
 */
var kthToLast = function(head, k) {
    if(head === null) return null;
    let first = head, second = head;
    let node = head;
    while(k > 0){
        first = first.next;
        k--;
    }
    console.log(first);
    while(first){
        second = second.next;
        first = first.next;
    }
    return second.val;
};

堆栈法

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {number}
 */
var kthToLast = function(head, k) {
    if(head === null) return null;
    let arr = [];
    let node = head;
    while(node && (node.val || node.val === 0)){
         arr.push(node.val);
         node = node.next;
    }
    return arr[arr.length - k];
};
上一篇下一篇

猜你喜欢

热点阅读