输入一个链表,从尾到头打印链表每个节点的值。
方法一:用栈
方法二:递归
方法三:使用java中的 Collections.reverse()
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 };