题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
http://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
首先我们要考虑的第一个点就是如果链表的长度小于K值的话,我们就直接返回null
然后我们就可以开始考虑这道题怎么进行解决了:
1.我们需要维护俩个指针,curLeft和curRight
2.我们先遍历这个链表,让curLeft走K步
3.然后我们继续遍历这个链表,这个循环结束的条件就是curLeft == null,因为curLeft在上一步的时候就已经走出了K步,所以我们这个时候让curLeft和curRight分别向前移动,直到curLeft == null的时候,这个时候的curRight就是我们所得的解。
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
ListNode cur = pHead;
int index = 0;
while (cur != null){
cur = cur.next;
index++;
}
if (index < k){
return null;
}
int left = 0;
ListNode curLeft = pHead;
ListNode curRight = pHead;
while (curLeft != null){
if (left != k){
curLeft = curLeft.next;
left++;
}else {
break;
}
}
while (curLeft != null){
curLeft = curLeft.next;
curRight = curRight.next;
}
return curRight;
}
}
SHEIN希音公司福利 246人发布