チェーンテーブルを末尾から印刷する

764 ワード

タイトル記述はチェーンテーブルを入力し,チェーンテーブル値が末尾から順にArrayListを返す.
考えはチェーンテーブルのvalをstackに保存しvectorに出力します.
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector printListFromTailToHead(ListNode* head) {
        vector vec;
        vec.clear();
        if(head == NULL)
            return vec;
        std::stack s;
        while(head != NULL)
        {
            s.push(head->val);
            head = head->next;
        }
        
        while(!s.empty())//        
        {
            vec.push_back(s.top());
            s.pop();
        }
        return vec;
    }
};