面试题6:从尾到头打印链表

93 阅读1分钟

题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

思路

  1. 每次访问一个节点,就将节点值传入vector,最后,翻转vector
  2. 每次访问一个节点,就将节点入栈
  3. 递归写法

代码

vector<int> reversePrint(ListNode* head) {
        vector<int>v;
        ListNode *p=head;
        while(p){
            v.push_back(p->val);
            p=p->next;
        }
        int l=0,r=v.size()-1;
        while(l<r){
            swap(v[l++],v[r--]);
        }
        return v;
    }
vector<int> reversePrint(ListNode* head) {
        stack<int>s;
        ListNode *p=head;
        while(p){
            s.push(p->val);
            p=p->next;
        }
        vector<int>v;
        while(!s.empty()){
            v.push_back(s.top());
            s.pop();
        }
        return v;
    }
class Solution {
public:
    vector<int>v;
    vector<int> reversePrint(ListNode* head) {
        if(head){
            reversePrint(head->next);
            v.push_back(head->val);
        }
        return v;
    }
};

递归的方法用时长,耗内存

题目链接(leetcode-cn.com/problems/co…)