链表中倒数第k个结点
题目描述:
输入一个链表,输出该链表中倒数第k个结点。
如果该链表长度小于k,请返回空。
示例1
输入
{1,2,3,4,5},1
返回值
{5}
Code:
/**
* 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
if(pHead == nullptr || k == 0)
return nullptr;
ListNode* pLeft = pHead;
ListNode* pRight = pHead;
//数目
for(unsigned int i = 0; i < k-1; i++)
{
if(pRight->next != nullptr)
pRight=pRight->next;
else
return nullptr;
}
//两边一起遍历
while(pRight->next!=nullptr)
{
pLeft=pLeft->next;
pRight=pRight->next;
}
return pLeft;
}
};