题目描述
输入一个链表,从尾到头打印链表每个节点的值。
思路1:用栈的方式(C++)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int>temp;//初始化一个栈
vector<int>res;//初始化一个容器
while(head){ //当链表不为空
temp.push(head->val); //入栈
head = head->next;
}
while(temp.size()){ //栈不为空
res.push_back(temp.top()); //从栈顶拿出值
temp.pop(); //出栈
}
return res;
}
};
思路2:
递归实现(C++)
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>res;
if(head != NULL){
res = printListFromTailToHead(head->next);
res.push_back(head->val);
}
return res;
}
};