5 Print the linked list from end to end

Enter a linked list and print the value of each node in the linked list from end to beginning.
  Method 1: Use stack
  Method 2: Recursion
  Method 3: Use Collections.reverse() in java

 

C++:

 1 /**
 2 *  struct ListNode {
 3 *        int val;
 4 *        struct ListNode *next;
 5 *        ListNode(int x) :
 6 *              val(x), next(NULL) {
 7 *        }
 8 *  };
 9 */
10 class Solution {
11 public:
12     vector<int> printListFromTailToHead(ListNode* head) {
13         if(head == NULL)
14             return vector<int>() ;
15         stack<int> s ;
16         vector<int> res ;
17         ListNode* p = head ;
18         while(p != NULL){
19             s.push(p->val) ;
20             p = p->next ;
21         }
22         while(!s.empty()){
23             res.push_back(s.top()) ;
24             s.pop() ;
25         }
26         return res ;
27     }
28 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324643975&siteId=291194637