剑指offer——倒数第k个节点

先走k-1步,然后判断fast有没有到空为止.

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        
        if(head==null||k<=0)
        {
            return null;
        }
        
        ListNode fast=head;
        ListNode slow=head;
        
        for(int i=1;i<k;i++)
        {
            if(fast.next!=null)
            {
                fast=fast.next;
            }
            else
            {
                return null;
            }
        }
        
        while(fast.next!=null)
        {
            fast=fast.next;
            slow=slow.next;
        }
        return slow;

    }
}
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/11073793.html