题目描述


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

如输入{1,2,3}的链表如下图:alt
返回一个数组为[3,2,1]


题解1:使用栈
代码:

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
//     vector<int> v;用于递归题解方式
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
//        栈操作
        ListNode * temp =head;
        stack<int> s;
        while(temp){
            s.push(temp->val);
            temp = temp->next;
        }
        vector<int> v;
        while(!s.empty()){
           v.push_back(s.top());
            s.pop();
        }
        return v;
    }
};

题解2:递归

代码:

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
//     vector<int> v;用于递归题解方式
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
//         递归操作,递归的本质是栈结构
        if(!head)
          return v; //递归结束

        ListNode * temp = head;
        if(temp->next){
            printListFromTailToHead(temp->next);
        }
        v.push_back(temp->val);
        return v;
    }
};

题解3:使用库函数reverse

代码

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
//     vector<int> v;用于递归题解方式
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
//         题解3:使用reverse函数
        vector<int>  v;
        ListNode *temp =head;
        while(temp){
            v.push_back(temp->val);
            temp=temp->next;
        }
        reverse(v.begin(),v.end());
        return v;
    }
};