链表的定义如下:
struct ListNode{ int m_nValue; ListNode* m_pNext;};ListNode* FindKthToTail(ListNode*pListHead, unsigned int k){ if (pListHead == NULL||k==0) { return NULL; } ListNode *pAhead = pListHead;//前面的结点 ListNode*pBehind = pListHead;//后面跟着的结点 //k = k - 1; //while (k != 0) //{ // if (pAhead->m_pNext) // { // pAhead = pAhead->m_pNext; // } // else // { // return NULL; // } // --k; //} for (unsigned int i = 0; i < k - 1; ++i)//当遇见无符号数时,一定要倍加小心,当比较时一定要类型一致 { if (pAhead->m_pNext != NULL) { pAhead = pAhead->m_pNext; } else { return NULL; } } //当前面的结点走到根节点时,后面的结点指向了倒数第k个结点 while (pAhead->m_pNext != NULL) { pAhead = pAhead->m_pNext; pBehind = pBehind->m_pNext; } return pBehind;}新闻热点
疑难解答