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

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

从头到尾遍历节点通过指针依次向后即可,从尾到头不一样,最后遍历到的最先输出,想到可以通过栈来实现。

在LeetCode中,函数的返回值是一个vector<int>,为了方便就用了reverse方法,时间复杂度会高一点。

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ans;
        while(head){
            ans.push_back(head->val);
            head = head->next;
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

另外vector有insert方法,可以在头部插入。

posted @ 2021-11-13 13:03  三年终  阅读(20)  评论(0)    收藏  举报