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

题目:
输入一个单向链表,输出该链表中倒数第k个结点,
链表的倒数第0个结点为链表的尾指针

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

算法伪代码

initialize 2 pointer,let them point to link's head

let q move index k

//now p is differ k with q
when q get into the end, the p's position is we want
return 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;



你可能感兴趣的:(算法)