题目:
输入一个链表,从尾到头打印链表每个节点的值。
思路:
很容易想到用栈实现,后进先出;遍历一遍节点压栈,弹出栈的数值;也可以用递归实现;
代码:
递归版:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
if(head==NULL) return res;
if(head->next!=NULL) printListFromTailToHead(head->next);
res.push_back(head->val);
return res;
}
用栈实现:
//c++
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
if(head==NULL) return res;
ListNode* p=head;
stack<int> q;
while(p!=NULL){
q.push(p->val);
p=p->next;
}
while(!q.empty()){
res.push_back(q.top());
q.pop();
}
return res;
}