题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
涉及到链表顺序,这道题可以用双指针来跑。让指针①先跑k-1个结点,然后指针②跟着一起跑,等指针①到链表的最后一个结点了,指针②就指向倒数第k个结点(这里认为最后一个结点是倒数第1个,所以要跑k-1个结点)。
Code
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function FindKthToTail(head, k)
{
// write code here
if(head===null||k<=0)
return null;
let pNode1=head,pNode2=head;
let v=k;
while(--v){
if(pNode2.next!==null){
pNode2=pNode2.next;
}else{
return null;
}
}
while(pNode2.next!==null){
pNode1=pNode1.next;
pNode2=pNode2.next;
}
return pNode1;
}
运行环境:JavaScript (V8 6.0.0)
运行时间:12ms
占用内存:5336k