0
点赞
收藏
分享

微信扫一扫

剑指offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表 - 力扣(LeetCode) (leetcode-cn.com)

方案1

遍历一遍链表,把所有元素按正序放进一个数组里面,并得出栈的元素个数,此时再将数组逆序输出。

运行结果

代码

class Solution {
#define scale 0x2710
public:
    vector<int> reversePrint(ListNode* head) {
        int* arr = new int[scale];
        int count = 0;
        for (ListNode* iter = head; iter != NULL; iter = iter->next)
            arr[count++] = iter->val;
        vector<int> ans(count);
        for (auto& x : ans)
            x = arr[--count];
        return ans;
    }
};

方案2

 遍历是从头到尾,输出是从尾到头,典型的后进先出,可以考虑用栈:遍历的时候逐个压栈,最后从栈中逐个取出。(不难实现,这里就不放代码了)

既然想到了用栈来实现,递归在本质上就是一个栈结构,于是很自然地又想到了用递归来实现。我们每访问一个节点,首先递归输出它后面的节点,然后再输出该节点自身,这样整个链表的输出结果就反过来了。

运行结果

代码

class Solution {
    vector<int> ans;
public:
    vector<int> reversePrint(ListNode* head) {
        _reverse(head);
        return ans;
    }

    void _reverse(ListNode* node) {
        if (node) {
            _reverse(node->next);
            ans.push_back(node->val);
        }
    }
};
举报

相关推荐

0 条评论