AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
  • 吐槽
  • 登录/注册

AcWing 17. 从尾到头打印链表    原题链接    简单

作者: 作者的头像   米多奇香米饼 ,  2023-01-23 11:41:27 ,  所有人可见 ,  阅读 27


0


算法1 数组reverse

定义一个vector数组,将链表遍历一遍目的是将链表中的val放到数组中,最后将数组反转

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> printListReversingly(ListNode* head) {
        vector<int> res;
        while(head){
            res.push_back(head->val);
            head=head->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

算法2 非尾部递归

递归有两种形式,第一种是尾递归,第二种叫非尾部递归。
通俗来讲,尾递归是正序的,将输出语句放在递归语句的前面;而非尾部递归是逆序的,把输出语句放到递归语句的后面。
再来分析一下这道题,“从尾到头”很明显是逆序的,所以使用非尾部递归。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> printListReversingly(ListNode* head) {
        vector<int> res;
        while(head){
            res.push_back(head->val);
            head=head->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息