算法学习五---输出链表中倒数第k个结点

来源:互联网 发布:c语言动画代码大全 编辑:程序博客网 时间:2024/05/17 09:27
题目:
输入一个单向链表,输出该链表中倒数第k个结点,
链表的倒数第0个结点为链表的尾指针

算法思路:定义两个指针p,qZ指向链表头,然后让q向后移k个偏移量,此时p,q相差距离为k,然后再让p,q同时向后移,直到q指向链表尾,此时p的值就是所要求的

算法伪代码

initialize 2 pointer,let them point to link's headlet q move index k//now p is differ k with qwhen q get into the end, the p's position is we wantreturn p's data


C++实现

//initialize 2 pointer    ChainNode<T> *p, *q;    p = q = first;    //let q move index k    for(int i = 0; i != k; ++i)    {        q = q->link;    }    //now p is differ k with q    //when q get into the end, the p's position is we want    while(q != NULL)    {        p = p->link;        q = q->link;    }        //return p's data    return p->data;



0 0