首页 > 其他 > 详细

【剑指Offer-06】从尾到头打印链表

时间:2021-02-15 10:00:37      阅读:22      评论:0      收藏:0      [点我收藏+]

问题

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

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

示例

输入:head = [1,3,2]
输出:[2,3,1]

解答1:栈

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        if (!head)
            return {};
        vector<int> res;
        ListNode* node = head;
        stack<int> s;
        while (node->next) {
            s.push(node->val);
            node = node->next;
        }
        s.push(node->val);
        while (!s.empty()) {
            res.push_back(s.top());
            s.pop();
        }
        return res;
    }
};

重点思路

遍历链表,将对应值依次压入栈。再将栈中数据依次pop到结果数组中。

解答2:递归

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        if (!head)
            return {};
        vector<int> res = reversePrint(head->next);
        res.push_back(head->val);
        return res;
    }
};

重点思路

栈可以压入数字结果,同样也可以压入函数,后者即为递归做法。使用递归代码会更加简洁,但是要注意当链表很长时可能导致函数调用栈溢出。

【剑指Offer-06】从尾到头打印链表

原文:https://www.cnblogs.com/tmpUser/p/14401747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!