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}