4. 從尾到頭打印鏈表

1  題目描述

       輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。

2  思路

       棧、遞歸、reverse

3  代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    vector<int> reversePrint(ListNode* head) {
        //reverse
        /*
        while(head) {
            res.push_back(head->val);
            head = head->next;
        }
        //使用algorithm算法中的reverse反轉res
        reverse(res.begin(), res.end());
        return res;
        */

        //棧
        /*
        stack<int> s;
        //入棧
        while(head) {
            s.push(head->val);
            head = head->next;
        }
        //出棧
        while(!s.empty()) {
            res.push_back(s.top());
            s.pop();
        }
        return res;
        */

        //遞歸

        if(head == nullptr) {
            return res;
        }
        reversePrint(head->next);
        res.push_back(head->val);
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章