1. 程式人生 > >3,從尾到頭打印鏈表 《劍指offer》

3,從尾到頭打印鏈表 《劍指offer》

next 鏈表 ext cnblogs offer 打印 輸入 ron tac

題目:

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。

思路:

很容易想到用棧實現,後進先出;遍歷一遍節點壓棧,彈出棧的數值;也可以用遞歸實現;

代碼:

  遞歸版:

    vector<int> res;
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head==NULL) return res;
        if(head->next!=NULL) printListFromTailToHead(head->next);
        res.push_back(head->val);
        return res;
    }

  用棧實現:

//c++
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
        if(head==NULL) return res;
        ListNode* p=head;
        stack<int> q;
        while(p!=NULL){
            q.push(p->val);
            p=p->next;
        }
        while(!q.empty()){
            res.push_back(q.top());
            q.pop();
        }
        return res;
    }

  

3,從尾到頭打印鏈表 《劍指offer》