0
点赞
收藏
分享

微信扫一扫

力扣刷题笔记丨算法数据结构--链表--从尾到头打印链表

鲤鱼打个滚 2022-02-14 阅读 97

1 题目分析

链表结构

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

2 代码实现

思路一:遍历时,每次将当前节点的值插入list的最前端 

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> myList;
        while (head != NULL)
        {
            myList.insert(myList.begin(), head->val);
            head = head->next;
        }
        return myList;
    }
};

结果:速度上比较慢

 思路二:递归法,当指针为空时终止递归

class Solution {
public:
    void recursion(vector<int>&v,ListNode*node){
        if(!node)return;
        recursion(v,node->next);
        v.emplace_back(node->val); //每次回溯时把当前数值加入列表
    }
    vector<int> reversePrint(ListNode* head) {
        vector<int> ret;
        recursion(ret,head);
        return ret;
    }
};


结果:速度很快

 

举报

相关推荐

0 条评论