思路:
给出两个指针pFast和pSlow,先让pFast指针走K步,再同时走两个指针。
当pFast走到结尾的时候,此时的pSlow为倒数第K个节点。
ListNode* FindKNode(ListNode* pHead,int k)
{
if(k<=0 || pHead ==NULL )
return NULL;
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while(k!=0 && pFast != NULL)
{
k--;
pFast = pFast->Next;
}
//这里可能k>链表长度,所以判断pFast是否为空
if(pFast == NULL)
return NULL;
while(pFast != NULL)
{
pFast = pFast->Next;
pSlow = pSlow->Next;
}
return pSlow;
}