AcWing 33. 链表中倒数第k个节点
原题链接
简单
作者:
飞呀
,
2021-05-15 11:31:18
,
所有人可见
,
阅读 225
/**
* 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 == NULL) return NULL;
ListNode* cur = pListHead;
int n = 1;
while(cur->next != NULL){
cur = cur->next;
n++;
}
if(k > n) return NULL;
int add = n - k;
cur = pListHead;
while(add--){
cur = cur->next;
}
cur->next = NULL;
return cur;
}
};