遞歸實現
class Solution {
private:
vector<int> result;
public:
vector<int> printListFromTailToHead(ListNode* head) {
if(head != NULL)
{
if(head->next!=NULL)
{
printListFromTailToHead(head->next);
}
result.push_back(head->val);
}
return result;
}
};
借助棧實現
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode *pnode = head;
vector<int> result;
stack<int> myresult;
while(pnode!=NULL)
{
myresult.push(pnode->val);
pnode=pnode->next;
}
while(!myresult.empty())
{
result.push_back(myresult.top());
myresult.pop();
}
return result;
}
};