/*
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 slow = head,fast = head;
int i = 0;
//快指针先走K步
while(i<k && fast !=null){
fast = fast.next;
i++;
}
//链表太短了
if(i<k && fast == null)
return null;
while(fast != null){
slow = slow.next;
fast =fast.next;
}
return slow;
}
}
题目描述
/*
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 slow = head,fast = head;
int i = 0;
//快指针先走K步
while(i<k && fast !=null){
fast = fast.next;
i++;
}
//链表太短了
if(i<k && fast == null)
return null;
while(fast != null){
slow = slow.next;
fast =fast.next;
}
return slow;
}
}
输入一个链表,输出该链表中倒数第k个结点。