您的位置:首页 > 其它

返回单链表的倒数第n个节点

2016-02-23 11:52 351 查看
struct list_node {

    struct list_node *next;

    void *data;

};

/*

这个函数的名字起得不是特别的好。

功能就是返回单链表倒数第n个节点。

参数说明:

struct list_node *head:单链表头指针

unsigned int pos:倒数的个数

*/

struct list_node *get_last_nth_node(struct list_node *head, unsigned int pos)

{

    struct list_node *ret = head;

    unsigned int i = 0;

    /* 向前步进pos个节点,因为链表个数可能不足,所以需要判断head值是否有效 */

    while (head && i < pos) {

        ++i;

        head = head->next;

    }

    /* head为NULL的话,说明链表个数不足,返回NULL */

    if (!head) {

        return NULL;

    }

    /* 

    让ret与head同步向后步进,这样保证了ret与head之间的距离为pos。

    这样当head到达最后一个节点的时候,ret即为所求的值。

    */

    while (head->next) {

        ret = ret->next;

        head = head->next;

    }

    return ret;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: