The reciprocal k node in the linked list __ algorithm

Source: Internet
Author: User

This is the sword refers to the offer of a very classic problem, but also in the interview written in the high-frequency appearance. The detailed description of the topic is as follows: Enter a list and output the reciprocal K-nodes in the list. In order to conform to the habits of most people, counting starts at 1, that is, the tail node of the linked list is the last one.

There is a very intuitive solution, that is, scan the list two times, the first time used to record the length of the linked list N, the second from the head of the linked list (n-k+1) step, found that node is the penultimate K node. The problem with this algorithm is that you need to scan the list two times, which is not particularly smart.

In fact, think about this algorithm model and the form of the stack is very similar, we just start from scratch to scan the list, the scan to each node into the stack, after the scan, in turn, pop from the stack element, pop-up of the K element is the penultimate element.

In addition, we have a more general solution. is to use two pointers, the first pointer to go first k-1 step, the second pointer to stop at the first element, and then the two pointers synchronized to the back of the list scan, when the first pointer to the last element, then the second pointer to the bottom of the K-th node. I will use code to implement this algorithm, complete code upload to Https://github.com/chenyufeng1991/BackwardsKNode.

The core code is as follows:

void Printbackwordk (node *phead, int k)
{
    node *front = phead;
    Node *behide = phead;
    int origink = k;

    while (--k)
    {
        front = front->next;
    }

    while (Front->next!= NULL)
    {
        front = front->next;
        Behide = behide->next;
    }

    cout << "penultimate" << origink << "elements are:" << behide->element << Endl;

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.