高效的查找算法:
找出单向链表的倒数第m个元素
Node* FindMToLastNode(Node* pHead, int m)
{
// 查找到第m个元素
Node* pCurrent = pHead;
for (int i = 0; i < m; ++i)
{
if (pCurrent)
{
pCurrent = pCurrent->next;
}
else
{
return NULL;
}
}
// 一起继续遍历到链表尾部,
// 现在pFind和pCurrent之间间隔了m个元素,
// 所以,当pCurrent遍历到尾部的时候,
// pFind就到了倒数第m个元素的位置上.
Node* pFind = pHead;
while (pCurrent)
{
pFind = pFind->next;
// 间隔m个元素
pCurrent = pCurrent->next;
}
return pFind;
}这个算法果然精妙!空间上只需要开销两个临时变量,时间上只需要循环链表一遍,也就是O(n)!
下面还有更加精炒的
下面还有更加精炒的
//查找倒数第k个元素并删除。
void NodeTest::RemoveIndexNode(Node *head, int k)
{
Node *p1 = head;
Node *p2 = head;
Node *pLast = NULL;
int c = -1;
while (p1) {
if (c == k) {
p2 = head;
}
p1 = p1->next;
p2 = p2->next;
pLast = p2;
c++;
}
if (c >= k) {
Node *pTemp = pLast->next;
pLast->next = pLast->next->next;
delete pTemp;
}else
{
printf("Is not find in the index of k elements.\n");
}
}
本文介绍了一种高效的算法来查找单向链表的倒数第m个元素,并演示了如何在此基础上实现删除倒数第k个元素的功能。该算法仅需线性时间复杂度O(n),空间复杂度为常数级别,通过双指针技巧简化了操作。
5998

被折叠的 条评论
为什么被折叠?



