- 使用stack
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
stack<ListNode*> nodes;
ListNode* pNode = head;
while(pNode != NULL) {
nodes.push(pNode);
pNode = pNode->next;
}
while(!nodes.empty()) {
pNode = nodes.top();
res.push_back(pNode->val);
nodes.pop();
}
return res;
}
};
- 递归
class Solution {
public:
vector<int> res;
void func(ListNode* head) {
if(head != NULL) {
if(head->next !=NULL)
func(head->next);
res.push_back(head->val);
}
}
vector<int> reversePrint(ListNode* head) {
func(head);
return res;
}
};