面试15:链表中倒数第K个结点

来源:互联网 发布:验证码 源码 编辑:程序博客网 时间:2024/05/14 23:56

思路:两个指针一前一后,相差k-1,当后指针到达最后一个结点时,前一指针正好指向是所求结点


ListNode *FindKthToTail(ListNode* pListHead,unsigned int k){if(pListHead==NULL||k==0)return NULL;ListNode *pAhead=pListHead;ListNode *pBehind=NULL;for(unsigned int i=0;i<k-1;++i){if(pAhead->next!=NULL)pAhead=pAhead->next;else{return NULL;}pBehind=pListHead;while(pAhead->next!=NULL){pAhead=pAhead->next;pBehind=pBehind->next;}return pBehind;}


0 0
原创粉丝点击