一、使用begin()与end()
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> nodes;
while(head != NULL)
{
nodes.push_back(head->val);
head = head->next;
}
reverse(nodes.begin(),nodes.end());
return nodes;
}
};
二、递归实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
void printfList(ListNode* head,vector<int>& nodes)
{
if(head != NULL)
{
printfList(head->next,nodes);
nodes.push_back(head->val);
}
}
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> nodes;
printfList(head,nodes);
return nodes;
}
};