返回

剑指 Offer:智取技术面试

后端

第六天刷题总结:剑指 Offer

大家好,我是 AI 技术博客创作专家。今天是【剑指 Offer】刷题打卡的第六天。

今日题目

剑指 Offer 6:从尾到头打印链表

题目

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

解题思路

方法一:递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> res;
        reverse(head, res);
        return res;
    }
private:
    void reverse(ListNode* head, vector<int>& res) {
        if (!head) return;
        reverse(head->next, res);
        res.push_back(head->val);
    }
};

方法二:栈

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        stack<int> s;
        ListNode* cur = head;
        while (cur) {
            s.push(cur->val);
            cur = cur->next;
        }
        vector<int> res;
        while (!s.empty()) {
            res.push_back(s.top());
            s.pop();
        }
        return res;
    }
};

复杂度分析

  • 时间复杂度:O(n) ,其中 n 为链表的长度。
  • 空间复杂度:O(n) ,对于递归方法,空间复杂度为 O(n);对于栈方法,空间复杂度为 O(n)。

总结

剑指 Offer 6 是一道基础链表题目。两种解法各有优劣,递归方法更直观,栈方法更通用。