//求解思路:首先创建前后两个指针同时指向头结点,前指针移动到k-1,就是第k个节点,此时前后两个指针一起移动到前指针移动到链表末尾,此时后指针的位置就是倒数第k个节点的位置
//让第一个指针指向 k-1 第二个指针指向0 二者一起移动,当移动到终点此时便有第二个指针指向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) {
if(head == null || k <= 0){
return null;
}
ListNode pre = head;
ListNode in = head;
for(int i = 0; i < k; i++){
if(pre.next != null){
pre = pre.next;
}
else{
return null;
}
}
while(pre.next != null && in.next !=null){
pre = pre.next;
in = in.next;
}
return in;
}
}
还有一种方法差不多写法思路是一样的
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
//求解思路:让第一个指针指向 k-1 第二个指针指向0 二者一起移动,当移动到终点此时便有第二个指针指向k返回该值即可
if(head == null || k <= 0){
return null;
}
ListNode pre = head;
ListNode in = head;
for(int i = 1; i < k; i++){
if(pre.next != null){
pre = pre.next;
}else{
return null;
}
}
while(pre.next != null && in.next != null){
pre = pre.next;
in = in.next;
}
return in;
}
}