分享

剑指offer 03 从尾到头打印链表

 雪柳花明 2017-05-19

题目描述

输入一个链表,从尾到头打印链表每个节点的值。


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

//利用栈的先进后出
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<ListNode*> Sta;//栈
        
        vector<int> res;
        
        ListNode *pNode=head;
        while(pNode!=NULL){
            Sta.push(pNode);
            pNode=pNode->next;
        }
        
        while(!Sta.empty()){
            pNode=Sta.top();
            res.push_back(pNode->val);
            Sta.pop();
        }
        
        return res;
    }
};

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


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约