美文网首页
leetcode-day19-返回倒数第 k 个节点[面试题 0

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

作者: 孙静静 | 来源:发表于2020-11-05 17:18 被阅读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];
    };
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/beravktx.html