剑指Offer-链表-(2)

知识点/数据结构:链表

题目描述
输入一个链表,输出该链表中倒数第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){
            return null;
        }
        ListNode pre= head;
        ListNode  x= head;
        for(int i=0;i<k-1;i++){//这里是k-1;非常重要!!!
            if(pre.next!=null){
                pre=pre.next;
            }else{
                return null;
            }    
        }
        while(pre.next!=null){
            pre = pre.next;
            x = x.next;
        }
        return x;
    }   
}

猜你喜欢

转载自blog.csdn.net/qq_35649064/article/details/84791477
今日推荐