链表中倒数第k个结点
程序员文章站
2022-03-02 10:12:06
题目描述输入一个链表,输出该链表中倒数第k个结点。题目链接:https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&&tqId=11167&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking代码:/*struct ListNode {int val;str...
题目描述
输入一个链表,输出该链表中倒数第k个结点。
代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(k<=0||pListHead==NULL) return NULL;
ListNode *fast=pListHead,*slow=pListHead;
int tmp=k;
while(tmp--)
{
if(fast) fast=fast->next;
else return NULL;
}
while(fast)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
};
本文地址:https://blog.csdn.net/chimchim04/article/details/107284993