一、题目
题目描述
输入一个链表,输出该链表中倒数第k个结点。
如果该链表长度小于k,请返回空。
示例1
输入
{1,2,3,4,5},1
返回值
{5}
二、思路
遍历两次链表,第一次统计节点总个数;第二次返回倒数第k个数
三、代码
/**
* 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) {
if(pHead==nullptr)
{
return nullptr;
}
int Count=0;
ListNode *curr=pHead;
while(curr !=nullptr)
{
Count+=1;
curr=curr->next;
}
if(Count<k)
{
return nullptr;
}
ListNode *Node=pHead;
int num=0;
while(Node !=nullptr)
{
if(num==Count-k)
{
return Node;
}
num+=1;
Node=Node->next;
}
return nullptr;
}
};