Recursive algorithm (2)-linked list traversal
In recursion (1), the idea of recursion is simply introduced, and a simple example is given to illustrate how recursion works, and the implementation of recursion is represented by a linear structure. Linear is because it is easy to understand, if the use of tree structure, will increase the difficulty of the problem, not conducive to beginners to understand the idea of recursion.
Why use recursion
about why with recursion, my personal understanding is that recursion does not violate the original intention of the algorithm, that is, expecting to pass the XXX value, processed to return the value of XXX. Do not recursive to recursive, it is easy to create a singular function semantics. In addition, by recursion, you can make the code more neat, short, exquisite, beautiful. Of course, there will be a certain degree of performance loss, but reasonable use, for that part of the loss can be negligible.
Let's take a single-linked list as an example to understand how recursion works.
1. traversing a single linked list
Cycle |
Recursive |
Private void Traveserl (Lnode head) { ifnull) return; while NULL ) { Console.WriteLine (p.data); = p.next; } } |
private void Traveserr (Lnode head) { if (head = = null) return; Console.WriteLine (head.data); Traveserr (Head.next);}
|
For loop traversal I don't want to say more. However, it is worth noting that recursive traversal, first printing the data, and then traversing the next node. Interestingly, if you put a print statement behind a recursive call, it will be printed in reverse order.
Analysis
Assuming the structure of the list is like this
A->b->c->d->e->f
The following happens when a recursive call occurs
1 . Print before recursive call (meaning to print when entering the body of the function)
(1 ) Enter function (read from left to right)
A-> |
B-> |
C-> |
D-> |
E-> |
F-> |
Print a |
Print B |
Print C |
Print D |
Print E |
Print F |
Output: A, B, C, D, E, F.
(2 ) when the function exits (right to left degrees)
<-a |
<-b |
<-c |
<-d |
<-e |
<-f |
Empty |
Empty |
Empty |
Empty |
Empty |
Empty |
2. after a recursive call (meaning that only the function body is exited before printing)
(1) Enter function body (read from left to right)
A-> |
B-> |
C-> |
D-> |
E-> |
F-> |
Empty |
Empty |
Empty |
Empty |
Empty |
Empty |
(2) exit the function body (read from right to left)
<-a |
<-b |
<-c |
<-d |
<-e |
<-f |
Print a |
Print B |
Print C |
Print D |
Print E |
Print F |
Output: F, E, D, C, B, A
Conclusion: When the operation is performed after a recursive call, the operation is performed from the back forward to the linked list. This is also one of the features of the stack. Of course, when the specific decision, depending on the programmer himself, is to start from the beginning of the sequence of operations, or back to the previous reverse operation, specific problems specific analysis.
[Original] algorithm recursion (2)-linked list traversal