Returns the m element in the descending order of a one-way linked list.

Source: Internet
Author: User

The original question of a game company is as follows: for a one-way linked list, try to write a function that finds its reverse order of the m element (m> = 1, pay attention to variable naming, annotations, time complexity, and space complexity. Note: Compile the code that can be compiled and run.

The conventional practice or first thought of intuition is to first obtain the length of the linked list, that is, the total number of elements n, and then the problem is converted to the order of n-m + 1 element. However, because this method requires the length to be calculated first, and the traversal is performed once more, the efficiency is not high and the cohesion is not high. Because the calculation depends on the length, and this operation can be completely independent, in order to maximize cohesion and reduce the dependence on other operations, we need to think further to find a simpler and more efficient algorithm. In fact, we can do this by first finding the m element in sequence, use a pointer P to point to this element and another pointer PR to point to the head of the linked list. Now, P and PR move to the right at the same time until P is empty, PR is the m-th element in the descending order required. If m exceeds the limit, PR is empty, indicating that it cannot be found. In this way, only one traversal is required. The C ++ code is described as follows:
1 template <typename T>
2 struct Node
3 {
4 T data;/** // <data
5 Node * next; // <pointer to the next Node
6 };
7
8 template <typename T>
9 Node <T> * ReverseFind (Node <T> * head, size_t m)
10 {
11 size_t n = 0;
12 Node <T> * p, * pR = NULL;
13 for (p = head; p = p-> next)
14 {
15 if (++ n = m)
16 {
17 pR = head;
18 continue;
19}
20 if (pR)
21 {
22 pR = pR-> next;
23}
24}
25 return pR;
26}

Related Article

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.