求链表中倒数第K个节点

1、求链表中倒数第K个节点

 

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)
        {
                pAhead = pAhead->m_pNext;
		if(pAhead == NULL)
			return NULL;
        }
 
        pBehind = pListHead;
 
        while(pAhead->m_pNext != NULL)
        {
                pAhead = pAhead->m_pNext;
                pBehind = pBehind->m_pNext;
        }
 
        return pBehind;
}

 

要注意一些错误处理机制;

转自:http://blog.csdn.net/cadcisdhht/article/details/6197041

 

 

posted @ 2013-04-17 20:18  javawebsoa  Views(136)  Comments(0Edit  收藏  举报