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

输入一个链表,从尾到头打印链表每个节点的值。 
输入描述: 输入为链表的表头
输出描述: 输出为需要打印的“新链表”的表头
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector printListFromTailToHead(struct ListNode* head) {
        ListNode* p=head;
        vector v;
        stack s;
        if(p==NULL) return v;
        while(p!=NULL){
            s.push(p->val);
            p=p->next;
        }
        while(!s.empty()){
            v.push_back(s.top());
            s.pop();
        }
        return v;
    }
};


你可能感兴趣的:(剑指offer)