class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
//以防万一,我先检查是否为空
if(head == null){
return null;
}
ListNode temp = head;
int length = 0;
//第一次遍历,找出链表的长度
while(true){
if(temp.next==null){
break;
}
length++;
temp = temp.next;
}
//反向思路,求倒数第k个节点,就从前向后遍历length-k,
//因为这里第一个head也有数据,所以+1
temp =head;
for(int i=0;i<(length-k+1);i++){
temp = temp.next;
}
return temp;
}
}
08-22
935
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-22
1007
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
1163
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)