题目描述
输入一个链表,从尾到头打印链表每个节点的值。
递归和栈
递归如下:
/**
* 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;
print(head, res);
return res;
}
void print(ListNode* head, vector<int>& res){
if(head == NULL)
return;
print(head->next, res);
res.push_back(head->val);
}
};
栈如下:
/**
* 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;
stack<ListNode*> s;
while(head){
s.push(head);
head = head->next;
}
while(!s.empty()){
res.push_back(s.top()->val);
s.pop();
}
return res;
}
};