题目
思路
Code
使用栈:
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { stack<int> a; vector<int> res; while(head) { a.push(head->val); //将元素入栈 head = head->next; } while(!a.empty()) //当栈中元素不为空时 { res.push_back(a.top()); //读取栈顶元素放入vector向量 a.pop(); //弹出栈顶元素 } return res; } };
递归:
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { //使用递归实现 vector<int> res; if(!head) //退出条件 return res; res = printListFromTailToHead(head->next); //这里必须有res返回值 res.push_back(head->val); return res; } };
reverse()函数:
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> res; while(head) { res.push_back(head->val); head = head->next; } reverse(res.begin(),res.end()); return res; } };