力扣:面试题 02.02. 返回倒数第 k 个节点

This commit is contained in:
huangge1199 2021-02-05 15:00:14 +08:00
parent a22185ce4c
commit ba8950b3c2

View File

@ -0,0 +1,23 @@
package com.code.leet.study.t20210205;
import com.code.leet.entiy.ListNode;
/**
* 实现一种算法找出单向链表中倒数第 k 个节点返回该节点的值
*/
public class KthToLast {
public int kthToLast(ListNode head, int k) {
ListNode p;
int count = 1;
p = head;
while (p.next != null) {
count++;
p = p.next;
}
p = head;
for (int i = 0; i < count - k; i++) {
p = p.next;
}
return p.val;
}
}