5-Print linked list from tail to head

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.