Title Description: http://ac.jobdu.com/problem.php?pid=1511
Enter a list to print the values of each node of the list from the end of the head.
Input:
Each input file contains only one set of sample test specimens.
Each set of test cases contains multiple lines, one integer greater than 0, representing the node of a linked list. The first line is the value of the first node in the list, and so on. When input to 1 indicates that the linked list is completed. -1 itself does not belong to the linked list.
Output:
Corresponds to each test case to output the value of each node of the list from the end of the tail, one row per value.
Reverse Print linked list, we traverse the list can only from beginning to end, now ask us from tail to head. Last-in, first-out , you can think of a stack to store traversed nodes, and then print out the stack sequence.
The essence of recursion is the stack structure , before printing this node, the next node of the print node is first hit .
#include <iostream>#include <stack>using namespace STD;classNode { Public:intVal Node* Next; Node (intVal, node* next = NULL) { This->val = val; This->next = Next; }};//Recursive implementationvoidPrintlistreversingrecur (node* head) {if(head = = NULL)return; Printlistreversingrecur (Head->next);cout<< Head->val <<" ";}//Stack implementationvoidPrintlistreversingstack (node* head) { Stack<Node*>S while(head! = NULL) {S.push (head); Head = head->next; } while(S.empty () = =false) {cout<< s.top ()->val <<" "; S.pop (); }cout<< Endl;}intMain () {node* head =NewNode (1,NewNode (2,NewNode (3,NewNode (4, NULL))); for(node* iter = head; ITER! = NULL; iter = iter->next)cout<< Iter->val <<" ";cout<< Endl;cout<<"Reverse print"<< Endl; Printlistreversingrecur (head);cout<< Endl; Printlistreversingstack (head);}
输出结果:1234 逆序打印43214321in0.4s]
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
5-Print linked list from tail to head