题目描述
输入一个链表,输出该链表中倒数第k个结点。
示例1
输入
1,{1,2,3,4,5}
返回值
{5
}
代码:
/*
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){//链表为空或k小于0;
return null;
}
ListNode fast = head;
ListNode slow = head;
while( k -1 != 0){//让fast先走k-1步;
if(fast.next !=null){//判断的是k值大于链表长度时
fast =fast.next;
k--;
}else{
return null;
}
}
while(fast.next != null){//未走到尾节点时,fsat和slow每次各走一步
fast = fast.next;
slow = slow.next;
}
return slow;//返回slow,为找到的倒数第n个节点;
}
}