3,从尾到头打印链表 《剑指offer》

题目:

输入一个链表,从尾到头打印链表每个节点的值。

思路:

很容易想到用栈实现,后进先出;遍历一遍节点压栈,弹出栈的数值;也可以用递归实现;

代码:

  递归版:

    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;
    }

  

posted @ 2017-09-04 13:13  llauser  阅读(137)  评论(0)    收藏  举报