The linked list node is defined as follows:
1 typedef struct ListNode2 {3 int value;4 ListNode *next;5 }TListNode;
As we all know, it is very easy to print a linked list from start to end, so we may first think of the reverse order of the linked list, and then print it from start to end, but the reverse order will damage the structure of the linked list, for the print operation, it is only a read operation. If the chain table structure is broken, it seems that it is not common sense. Is there a better solution? The answer is yes.
We know that to solve this problem, we need to print the last traversal node, and the last traversal node needs to be printed first, this is a typical example of "post-in-first-out". We can quickly think of using stacks to solve this problem. We only need to push the nodes into the stack in sequence during the time periods, the value of each node is output from the top of the stack to achieve the goal. The implementation code for this idea is as follows:
1 void PrintListReversing(TListNode *head) 2 { 3 stack<TListNode*> nodes; 4 5 TListNode *pnode = head; 6 while (NULL != pnode) 7 { 8 nodes.push(pnode); 9 10 pnode = pnode->next;11 }12 13 while (!nodes.empty())14 {15 pnode = nodes.top();16 17 cout << pnode->value << endl;18 19 nodes.pop();20 }21 }
Since we want to implement it with stacks, and Recursion itself is a stack structure, it is not difficult to come up with Recursive Implementation. The implementation code is as follows:
1 void PrintListReversing2(TListNode *head) 2 { 3 if (NULL != head) 4 { 5 if (NULL != head->next) 6 { 7 PrintListReversing2(head->next); 8 } 9 10 cout << head->value << endl;11 }12 }
The above implementation code is very concise, but if there are many knots in the linked list, it may cause function stack overflow, so we should avoid using it in actual encoding.