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