栈实现
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector <int> result;
if(head==NULL)
return result;
stack<ListNode*> nodes;
ListNode* pNode=head;
while(pNode!=NULL)
{
nodes.push(pNode); //压入nodes栈中
pNode=pNode->next; //pNode指向下一个
}
while(!nodes.empty())
{
pNode=nodes.top(); // 取栈顶元素
result.push_back(pNode->val); //压入result栈中
nodes.pop(); // nodes继续出栈
}
return result;
}
};
递归实现
class Solution
{
public:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head)
{
if(head != NULL)
{
printListFromTailToHead(head->next);
res.push_back(head->val);
}
return res;
}
};