返回链表倒数第k个结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/muzhixi/article/details/89320178

常规题目。

需要注意的点有:1. 链表为空;2. k<=0; 3.链表长度不足k。

    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null || k<=0) return null;
        int count=0;
        ListNode firster,seconder;
        firster=head;
        seconder=head;
        while(firster!=null){
            firster=firster.next;
            count++;
            if(count>k){
                seconder=seconder.next;
            }
        }
        if(count<k){
            return null;
        }
        return seconder;
    }

猜你喜欢

转载自blog.csdn.net/muzhixi/article/details/89320178
今日推荐