要求:输入一个链表,输出该链表中倒数第k个结点。
ceshi测试用例
1.{}
2.1,{1,2,3,4,5,6}
3.7,{1,2,3,4,5,6}`
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
int length = 0; //遍历链表求出链表长度
ListNode cur = head;
while (cur != null) {
length++;
cur = cur.next;
}
if(k >length) {//如果k值大于链表长度返回空指针
return null;
}
if (head == null) {//如果链表为空返回空指针
return null;
}
ListNode fast = head;//快慢指针思想
ListNode slow = head;
while (k > 0) {
fast = fast.next;
k--;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}