题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
双指针,让右指针先走K步,然后在左右指针一起走,当又指针null后,返回左指针就是需要返回的。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
if(k <= 0 || pHead == null){
return null;
}
ListNode Ltemp = pHead; // 第一个指针
ListNode Rtemp = pHead;
for(int i = 1 ; i <= k ; i++){
if(Rtemp == null){
return null;
}
Rtemp = Rtemp.next;
}
if(Rtemp == null){
return pHead;
}
while(Ltemp != null){
Ltemp = Ltemp.next;
if(Rtemp.next == null){
return Ltemp;
}else{
Rtemp = Rtemp.next;
}
}
return null;
}
}
