美文网首页
链表中倒数第K个结点

链表中倒数第K个结点

作者: 小明今晚加班 | 来源:发表于2019-02-26 22:03 被阅读0次

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

我的Code如下:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        ListNode pre = head;
        int count = 0;
        while(head != null){
            count++;
            head = head.next;
        }
        if(k>count){
            return null;
        }
        for(int i=0; i<count-k; i++){
            pre = pre.next;
        }
        return pre;
    }
}

相关文章

网友评论

      本文标题:链表中倒数第K个结点

      本文链接:https://www.haomeiwen.com/subject/mbftuqtx.html