Home » C++ » The last K node in the list

The last K node in the list

in order to achieve a goal list traversal only, use the two pointer, the pointer to the beginning of the first step from the chain go forward traversal k-1 header, the second pointer remained motionless, starting from step k, two hands together, the distance between two pointers in k-1, when the tail pointer to the first the list, the second pointer is right in the penultimate position.

K node list

#include
Using namespace std;
Struct ListNode
{
Int m_nKey;
ListNode *m_pNext;
};
Void AddToTail (ListNode**, pHead, int, value)
{
ListNode* pNew = new, ListNode ();
PNew->m_nKey = value;
PNew->m_pNext = NULL;
If (*pHead = NULL)
*pHead = pNew;
Else
{
ListNode* pNode = *pHead;
While (pNode->m_pNext = = NULL)
PNode = pNode->m_pNext;
PNode->m_pNext = pNew;
}
}
ListNode* FindKthToTail (ListNode*, pListHead, unsigned, int, K)
{
ListNode* pAhead = pListHead;
ListNode* pBehind = NULL;
For (int, I = 0, I, < K - 1, i++)
PAhead = pAhead->m_pNext;
PBehind = pListHead;
While (pAhead->m_pNext = = NULL)
{
PAhead = pAhead->m_pNext;
PBehind = pBehind->m_pNext;
}
Return pBehind;
}
Int, main ()
{
ListNode* pHead = NULL;
For (int, I = 0, I, < 10, i++)
AddToTail (&pHead, I);
ListNode* pNode=FindKthToTail (pHead, 5);
Cout "pNode->m_nKey" endl;
}




Latest