剑指Offer-14-链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

/*
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){
            ListNode first = head;
            ListNode second = head;
            for(int i=0;i<k-1;i++){
                if(second.next!=null){
                    second = second.next;
                }
                else{
                    return null;
                }
            }
            while(second.next!=null){
                second = second.next;
                first = first.next;
            }
            return first;
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27378875/article/details/81161781