//题目描述:输入一个链表,输出链表该链表中倒数第k个节点。
<?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
function FindKthToTail($head, $k)
{
// 两种思路: 这是第一种
/* $len=0;
$tmp=$head;
while($head!==null){
$len++;
$head=$head->next;
}
if($k>$len){
return null;
}
for($i=0;$i<$len-$k;$i++){
$tmp=$tmp->next;
}
return $tmp;*/
// 这是第二种思路
$arr=[];
$len=0;
while($head!=null){
$arr[]=$head;
$len++;
$head=$head->next;
}
$res=array_reverse($arr);
//赋值
for($i=0;$i<$len-$k;$i++){
$arr[$i]->next=$arr[$i+1];
}
return $res[$k-1];
}
本文介绍了一种算法,用于找到链表中倒数第K个节点的方法。提供了两种实现思路,一种通过两次遍历,另一种使用数组存储节点再逆序查找。
392

被折叠的 条评论
为什么被折叠?



