牛客_JZ22 链表中倒数最后k个结点
时间:2022-11-25 12:30:00
(此题同力扣剑指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;
}
}