14.链表倒数节点

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

注意不能直接head遍历,head返回,head是root;

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

 

posted on 2019-04-06 16:25  归臻  阅读(75)  评论(0编辑  收藏  举报

导航