(此题同力扣上剑指offer:
https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/)
题目:
输入一个长度为 n 的链表,设链表中的元素的值为 ai ,返回该链表中倒数第k个节点。
如果该链表长度小于k,请返回一个长度为 0 的链表。
1:
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
if(pHead == null || k <= 0){
return null;
}
ListNode cur = pHead;
int num = 0;
for(;pHead != null;){
num++;
pHead = pHead.next;
}
if(num < k){
return null;
}
if(k == num){
return cur;
}
for(int i = 1; i <= num - k; i++){
cur = cur.next;
}
return cur;
}
}
2.快慢指针
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if(head == null || k < 1){
return null;
}
ListNode fast = head;
ListNode slow = head;
for(int i = k;i > 0;i--){
fast = fast.next;
}
while(fast != null){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}