牛客网 剑指offer_编程题—— 从尾到头打印链表(C++)

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

C++

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) 
    {
        vector<int> res;
        while(head)
        {
            res.push_back(head->val);
            head=head->next;
        }
        for(int i=0;i<res.size()/2;i++)
        {
            swap(res[i],res[res.size()-i-1]);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/85008135