题解 | #从尾到头打印链表#

从尾到头打印链表

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035

三种解法:

解法:栈

解法:递归

解法:先把值存到数组,然后逆序数组

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/

//解法:栈
#include <algorithm>
class Solution {
  public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        stack<int> s;
        while (head != NULL) {
            s.push(head->val);
            head = head->next;
        }
        while (!s.empty()) {
            res.push_back(s.top());
            s.pop();
        }
        return res;
    }
};

// 解法:递归
/*
#include <algorithm>
class Solution {
  public:
    void recursion(ListNode* head, vector<int>& vec) {
        if (head) {
            recursion(head->next, vec);
            vec.push_back(head->val);
        }
    }

    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        recursion(head, vec);
        return vec;
    }
};
*/



// 解法:先把值存到数组,然后逆序数组
/*
#include <algorithm>
class Solution {
  public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        while (head) {
            vec.push_back(head->val);
            head = head->next;
        }
        reverse(vec.begin(), vec.end());
        return vec;
    }
};
*/

#算法#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务