剑指offer:00倒数第k个节点
作者:互联网
解法一:双指针
坑:
1:k的越界判断,对其大于链表大小,小于0的的情况进行处理
2:当k值大于链表长度时,返回nullptr,而不是表头
C++
/* 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(nullptr == pListHead||k<0){ return pListHead; } ListNode* pAhead = pListHead; ListNode* pBehind = nullptr; for(unsigned int i=0;i<k-1;i++){ pAhead = pAhead->next; if(nullptr==pAhead){ return nullptr; } } pBehind = pListHead; while(pAhead->next!=nullptr){ pAhead=pAhead->next; pBehind=pBehind->next; } return pBehind; } };View Code
标签:00,pBehind,ListNode,offer,int,nullptr,next,pAhead,倒数第 来源: https://www.cnblogs.com/vactor/p/14399568.html