剑指offer第三题打印链表

[题目描述]输入一个链表,从尾到头打印链表每个节点的值。

【分析】链表的打印,可以使用栈。可以使用递归。

栈的方法:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> st;/*定义一个人空栈*/
        while(head!=nullptr)//头结点不能为空
            st.push(head->val),head=head->next;//从头结点开始一个个放入栈中
        vector<int> ret;//定义一个容器
        while(!st.empty())//判断在栈不为空的时候执行
            ret.push_back(st.top()),st.pop();//执行pop元素放入容器
        return ret;
    }
};
递归的方法:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ret;
        dfs(head,ret);
        return ret;
    }
    void dfs(ListNode *head,vector<int> &ret){
        if(head== nullptr)
            return ;
        dfs(head->next,ret);
        ret.push_back(head->val);
    }
};
头插法复杂度为O(n^2)
class Solution {
public:
        vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> v;
        while(head != NULL)
        {
            v.insert(v.begin(),head->val);
            head = head->next;
        }
        return v;
    }
};
反向迭代器:
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> v;
                        
        ListNode *p = head;
        while (p != nullptr) {
           v.push_back(p->val);
           p = p->next;
        }
        //反向迭代器创建临时对象
        return vector<int>(v.rbegin(), v.rend());
    }
};
使用库函数reverse:
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> value;
        if(head != NULL)
        {
            value.insert(value.begin(),head->val);
            while(head->next != NULL)
            {
                value.insert(value.begin(),head->next->val);
                head = head->next;
            }         
             
        }
        return value;
    }
};







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值