《剑指Offer》06 “从尾到头打印链表”(c++)

《剑指Offer》06 “从尾到头打印链表”(c++)

①原版(栈)

方法:建栈,基于循环实现(自头到尾push,自尾到头pop)

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        std::stack<ListNode*> nodes;
        vector<int> res;

        ListNode* pNode = head;
        while (pNode != nullptr) {
            nodes.push(pNode);
            pNode = pNode->next;
        }
        while (!nodes.empty()) {
            pNode = nodes.top();
            //printf("%d\t", pNode->val); //打印list
            res.push_back(pNode->val); //返回list
            nodes.pop();
        }
        return res;
    }
};

 

② 原版(递归)

递归本质:栈结构
缺点:当链表很长,函数调用层级很深,或导致函数调用栈溢出

错误代码 / 错误结果:

//错误代码,因res未调用在递归内调用,甚至反复初始化
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        if (head != nullptr) {
            if (head->next != nullptr) {
                printListFromTailToHead(head->next);
            }
            //printf("%d\t", head->val);
            res.push_back(head->val);
        }
        return res;
    }

在这里插入图片描述

正确代码(递归调用):

    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        TTH_res(head, res); //递归
        return res;
    }

    void TTH_res(ListNode* head, vector<int>& res) {
        if (head == nullptr) return;

        TTH_res(head->next, res);
        res.push_back(head->val);
    }

 

③reverse(arr.begin(), arr.end());

方法:直接利用reverse()函数做翻转

    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        while (head != nullptr) {
            res.push_back(head->val);
            head = head->next;
        }
        //std::reverse(res.begin(), res.end());
        reverse(res.begin(), res.end());
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值