[Sword to offer] print linked list from tail to head

Source: Internet
Author: User

Title Description Enter a list of values for each node of the list to print from the end of the header.  Returns the head node of the new linked list. Method One: Use a stack, or preferably vector.reverse
vector<int> Printlistfromtailtohead (structlistnode*head) {Stack<int>St; Vector<int>Rtn;  while(head) {St.push (head)-val); Head= head->Next; }             while(!St.empty ()) {                intTMP =St.top ();                St.pop ();            Rtn.push_back (TMP); }                        returnRtn; }

Method Two: recursion in essence is a stack structure, so it is natural to think of recursive return to achieve. To implement the output linked list, each access to a node, the first recursive output of the node behind it, and then output the node itself, so that the output structure of the list is reversed.

 vector<int  > PrintListFromTailToHead1 (struct  listnode* head" {vector  <int  > Rtn;            Print (head, RTN);         return   Rtn;  void  print (listnode* head, Vector<i NT  > &rtn) { if  (H EAD == NULL)  return  ;            Print (head ->next, RTN);        Rtn.push_back (head ->val); }

[Sword to offer] 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.