# 程序员面试题精选100题(09)－链表中倒数第k个结点[数据结构]

struct ListNode
{
int       m_nKey;
ListNode* m_pNext;
};

///////////////////////////////////////////////////////////////////////
// Find the kth node from the tail of a list
//        k         - the distance to the tail
// Output: the kth node from the tail of a list
///////////////////////////////////////////////////////////////////////
ListNode* FindKthToTail_Solution1(ListNode* pListHead, unsigned int k)
{
return NULL;

// count the nodes number in the list
unsigned int nNum = 0;
while(pCur->m_pNext != NULL)
{
pCur = pCur->m_pNext;
nNum ++;
}

// if the number of nodes in the list is less than k
// do nothing
if(nNum < k)
return NULL;

// the kth node from the tail of a list
// is the (n - k)th node from the head
for(unsigned int i = 0; i < nNum - k; ++ i)
pCur = pCur->m_pNext;

return pCur;
}

///////////////////////////////////////////////////////////////////////
// Find the kth node from the tail of a list
//        k         - the distance to the tail
// Output: the kth node from the tail of a list
///////////////////////////////////////////////////////////////////////
ListNode* FindKthToTail_Solution2(ListNode* pListHead, unsigned int k)
{
return NULL;

ListNode *pBehind = NULL;

for(unsigned int i = 0; i < k; ++ i)
{
else
{
// if the number of nodes in the list is less than k,
// do nothing
return NULL;
}
}

// the distance between pAhead and pBehind is k
// when pAhead arrives at the tail, p
// Behind is at the kth node from the tail
{
pBehind = pBehind->m_pNext;
}

return pBehind;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：程序员面试题精选100题(09)－链表中倒数第k个结点[数据结构] 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)