Uses iteration (non-recursion) and recursion to reverse the single-chain table
I have been talking about it for a long time, but many local Interviews still like to ask this question. In actual projects, it seems to be of little use. Why should I select a single-chain table for reverse storage? Why not use list (in C ++) or iterator (in any language )? Or push all the data into the stack and then pop up one by one. It's boring to say so much. See why I am opposed to pure algorithm interview in cool shell.
Iteration (non-recursion)AlgorithmDescription:
Set two temporary pointers, Prev and next, to mark the frontend and successor of the current node, direct the next pointer of the current node to the frontend, replace the frontend pointer with the current node, and replace the current node with next, move to the "back" until the linked list is empty (next is null ).
C/C ++ implementation:
1 Typedef Struct _ Node 2 { 3 Struct _ Node * Next; 4 Int Data; 5 } List; 6 7 List * reverse (list * Head) 8 { 9 If (List = Null) 10 Return ; 11 12 List * pre = Head; 13 List * cur = head-> Next; 14 List * Ne; 15 While (Cur! = Null) 16 { 17 Ne = cur-> Next; 18 Cur-> next = Pre; 19 Pre = Cur; 20 Cur = Next; 21 } 22 Head-> next = NULL; 23 Head = Pre; 24 25 Return Head; 26 }
Recursive Algorithm Description: to sort the current node in reverse order, first sort its successor nodes in reverse order, and then point the next of the last node in reverse order to the current node.
C/C ++ implementation:
1 List * recurreverse (list * P, list * Head) 2 { 3 If (P = NULL | p-> next = Null) 4 { 5 Head = P; 6 Return P; 7 } 8 Else 9 { 10 List * q = reverse (p-> Next, head ); 11 Q-> next = P; 12 Return P; 13 } 14 }
.