题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
/*class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
export function FindKthToTail(pHead: ListNode, k: number): ListNode {
// write code here
// let count = 0
// let p = pHead
// while(p !== null){
// count++
// p = p.next
// }
const count = getLinkLength(pHead)
let p = pHead
if(count < k)return null
//找到位置
const position = count - k
p = pHead
//返回该位置以及之后的节点
for(let i = 0;i < position;i++){
p = p.next
}
return p
}
function getLinkLength(pHead: ListNode):number{
if(!pHead)return 0
return getLinkLength(pHead.next) + 1
}

