链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点.

思路:先遍历整个链表while(current.next),得到链表长度,再遍历到k值

function ListNode(x){
    this.val = x;
    this.next = null;
}
function FindKthToTail(head, k)
{
    if(head==null){
        return null;
    }
    var count=1,current=head,num;
    while(current.next){
        count++;
        current=current.next;
    }
    current=head;
    num=count-k;
    while(num<0){
        current=current.next;
        num--;
    }
    return current;
  
}
module.exports = {
    FindKthToTail : FindKthToTail
};

posted @ 2017-06-06 10:38  我叫王自信  阅读(99)  评论(0)    收藏  举报