輸入一個(gè)鏈表羹蚣,輸出該鏈表中倒數(shù)第k個(gè)結(jié)點(diǎn)。
解:
利用JavaScript的特性朗鸠,我選擇將鏈表轉(zhuǎn)化為array蚯撩,(^-^)V
function ListNode(x){
this.val = x;
this.next = null;
}
function FindKthToTail(head, k)
{
var array = [];
var node = head;
while(node){
array.push(node);
node = node.next;
}
if(array.length<k)return;
return array[array.length-k].val;
}
開玩笑,正確的思路是醬紫的:
:兩個(gè)指針烛占,先讓第一個(gè)指針和第二個(gè)指針都指向頭結(jié)點(diǎn)胎挎,然后再讓第一個(gè)指正走(k-1)步,到達(dá)第k個(gè)節(jié)點(diǎn)忆家。然后兩個(gè)指針同時(shí)往后移動(dòng)犹菇,當(dāng)?shù)谝粋€(gè)結(jié)點(diǎn)到達(dá)末尾的時(shí)候,第二個(gè)結(jié)點(diǎn)所在位置就是倒數(shù)第k個(gè)節(jié)點(diǎn)了
function FindKthToTail(head, k)
{
var firP = head,lasP=head;
if(!head||(!head.next && k>1))return null;
if(k==0)return null;
if(k<0){
k = -k;
while(k>0){
if(lasP.next){
lasP = lasP.next;
}else{
return null;
}
k--;
}
return lasP;
}
var i = k;
while(i>0){
firP = firP.next;
if(!firP)return null;
i--;
}
while(firP = firP.next){
firP = firP.next;
lasP = lasP.next;
}
return lasP;
}