找出单向链表的倒数第m个元素


高效的查找算法:

 找出单向链表的倒数第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");
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值