1. Find the K-th node in the linked list
[Cpp]
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;
}
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;
}
Pay attention to some error handling mechanisms;