Print the list penultimate k nodes

The subject method is to use two hands, fast hands to go forward step k, slow pointer finger in the first position, and then they move forward at the same time, when the pointer quickly went to the end position, the position of the pointer slow It is the reciprocal of the k-th node.

 

// list of the penultimate node k
#include <the iostream>
#include <List>
the using namespace STD;

int the_k_back_node(list<int> list1, int k)
{
    if ((!list1.empty()) && (k<=list1.size()) && (k >0))
    {
        auto it_fast = list1.begin();
        auto it_slow = list1.begin();
        while (k--)
        {
            ++it_fast;
        }
        while (it_fast != list1.end())
        {
            ++it_fast;
            ++it_slow;
        }
        return *it_slow;
    }
    return NULL;
}


int main()
{
    int k;
    cin >> k;
    list<int> list1;
    for (int i = 0; i <=10; i++)
    {
        list1.push_back(i);
    }
    cout << the_k_back_node(list1, k) << endl;
    system("pause");
    return 0;

}

Published 27 original articles · won praise 8 · views 2120

Guess you like

Origin blog.csdn.net/hgxy123/article/details/104238904