剑指offer3

  • 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

方法1

先顺序存入vector,再反向读取vector.back()

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> array;
        ListNode *h = head;
        while(h != nullptr)
        {
            array.push_back(h->val);
            h = h->next;
        }
        vector<int> res;
        while(array.size() != 0){
           res.push_back(array.back());
           array.pop_back();
        }
        return res;
    }
};

方法2

用栈实现

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<ListNode*> nodes;
        ListNode *h = head;
        while(h != nullptr)
        {
            nodes.push(h);
            h = h->next;
        }
        vector<int> res;
        while(!nodes.empty())
        {
            h = nodes.top();
            res.push_back(h->val);
            nodes.pop();
        }
        return res;
    }
};

方法3

能用栈实现自然就能用递归实现

发布了253 篇原创文章 · 获赞 32 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_34788903/article/details/104891861