用单链表实现查找(获取)倒数第m个元素(转自IT博客网chlclan的博客)

面试题。知道肯定有简便算法,但当时只想到两遍循环这种超基础算法。。。

回来找了一下,列出其中一种。

原文地址:http://www.cnitblog.com/chlclan/archive/2006/06/23/12767.html

 

用单链表实现查找(获取)倒数第m个元素,当m=0时就是指单链表最后一个元素。
最佳算法之一:
 用两个指针,一个指向当前遍历的元素,CurPos,另外一个指向CurPos前第m个元素,
然后两个指针同时一直向单链表后序元素遍历,直到CurPos指向最后一个元素为止。

element *FindMToLast(element *head, int m){

    int i;

    element *CurPos, *MToCurPos;

    CurPos = head;

   

    for(i=0; i<m; i++){

        if(CurPos->next){

            CurPos = CurPos->next;

        }else{

            /* 不到M个元素*/

            return NULL;

        }

    }

   

    /*Start mbehind at beginning and advanced pointers

    *together until current hits last element

    */

   

    MToCurPos = head;

    while(current->next){

        current = current->next;

        MToCurPos = MToCurPos->next;

    }

    /*

    *MToCurPos now points to the element we were

    *searching for, so return it

    */

    return MToCurPos;

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值