14.链表倒数节点

Posted wzqingttian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

 

以上是关于14.链表倒数节点的主要内容,如果未能解决你的问题,请参考以下文章