做了个剑指Offer的题目目录,链接如下:
https://blog.youkuaiyun.com/mengmengdastyle/article/details/80317246
一、题目
输入一个链表,输出该链表中倒数第k个结点。
二、思路
(1) 先写出步骤,将各种情况考虑到
//1.为空
//2.拿到总长度
//3.大于总长度时,返回空
//4.小于总长度时,总数-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) {
//1.为空
if(head==null){
return null;
}
//2.拿到总长度
int count = 0;
ListNode n = head;
while(n != null){
n = n.next;
count++;
}
//3.大于总长度时,返回空
if(count<k){
return null;
}
//4.小于总长度时,总数-k
int mm = 1;
ListNode tem = head;
for (int i = 0; i < count - k; i++) {
tem = tem.next;
}
return tem;
}
}