题解 | #链表中倒数第k个结点#
链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pListHead ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k) {
// write code here
int number = 0;//记录链表节点个数
struct ListNode* cur = pListHead;
while (cur)
{
number++;
cur = cur->next;
}
if (k >= 0 && k <= number)//此处防止输入的k是负数或者超过number,不满足则走else返回NULL
{
int i = 0;
struct ListNode* ret = pListHead;
for (i = 0; i < number - k; i++)//倒数第k个节点我们只需要从头节点往后找number-k次即可
{
ret = ret->next;
}
return ret;
}
else
{
return NULL;
}
}
#链表#
查看19道真题和解析