链表中倒数第k个结点

题目描述:输入一个链表,输出该链表中倒数第k个结点。

实现语言:Java

/*
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 first=head;
        ListNode last=head;
        for(int i=0;i<k;++i){
            if(first!=null){
                first=first.next;
            }else{
                return null;
            }
        }
        while(first!=null){
            first=first.next;
            last=last.next;
        }
        return last;
    }
}
原文地址:https://www.cnblogs.com/xidian2014/p/10196116.html