本算法从下标1开始遍历 利用双指针的形式遍历, 大大提高了代码的查找速度:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if (pListHead == NULL || k ==0)
{
return NULL;
}
ListNode* pAhead = pListHead;
ListNode* pBhead = NULL;
for (unsigned int i = 0; i < k-1; i++)
{
if (pAhead->m_pNext != NULL)
{
pAhead = pAhead->m_pNext;
}
else
{
return NULL;
}
}
pBhead = pListHead;
while (pAhead->m_pNext != NULL)
{
pAhead = pAhead->m_pNext;
pBhead = pBhead->m_pNext;
}
return pBhead;
}
void Test()
{
printf("stat\n");
ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);
CoonnectListNode(pNode1, pNode2);
CoonnectListNode(pNode2, pNode3);
CoonnectListNode(pNode3, pNode4);
CoonnectListNode(pNode4, pNode5);
printf("exepectd result:4\n");
ListNode* pNode = FindKthToTail(pNode1, 1);
PrintListNode(pNode);
DestroyList(pNode1);
}