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

问题

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

 // 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 {};
        stack<int> s;
        vector<int> res;
        ListNode* cur = head;
        while (cur) {
            s.push(cur->val);
            cur = cur->next;
        }
        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;
    }
};

重点思路

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

posted @ 2021-02-14 12:13  tmpUser  阅读(26)  评论(0编辑  收藏  举报