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

从尾到头,可以通过栈临时存储:

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> list;
        while(head != NULL)
        {
            list.push_back(head->val);
            head = head->next; 
        }
        reverse(list.begin(),list.end());       //reverse()函数用于反转vector数组   
        return list;
    }
};

 

posted @ 2017-03-01 21:29  Forever-Road  阅读(557)  评论(0编辑  收藏  举报