AcWing 33. 链表中倒数第k个节点C++
原题链接
简单
作者:
沙漠绿洲
,
2020-08-19 22:07:43
,
所有人可见
,
阅读 387
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findKthToTail(ListNode* pListHead, int k) {
if(!pListHead || !pListHead->next) return nullptr;
auto cur = pListHead;
while(cur && k --){
cur = cur->next;
}
if(!cur && k) return nullptr;
auto ret = pListHead;
while(cur){
cur = cur->next;
ret = ret->next;
}
return ret;
}
};