题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
//题中可能会出现三种异常情况:链表为空,k小于等于0,k超出链表个数范围
if(pHead==nullptr||k<=0)//链表为空或k小于等于0时直接返回null
{
return nullptr;
}
ListNode *p1,*p2;
p1=pHead;
p2=pHead;
for(int i=k-1;i>0;i--)//让p2先前进k-1步
{
p2=p2->next;
if(p2==nullptr)//k超出链表范围也返回null
{
return nullptr;
}
}
while(p2->next!=nullptr)//p1,p2同时移动到链表尾端,p1指向的结点就是倒数第k个的开端
{
p1=p1->next;
p2=p2->next;
}
return p1;
}
};
查看14道真题和解析
