3、从尾到头打印链表

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/PZHU_CG_CSDN/article/details/81938582

题目描述

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

思路:
  先把链表里元素取出到 vector 容器,再将容器进行翻转。

代码:

vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> a;
        while(head != NULL){
            a.push_back(head->val);
            head = head->next;
        }
        reverse(a.begin(),a.end());
        return a;
    }

注意:再本地运行时,reverse() 方法需要引入头文件 #include

猜你喜欢

转载自blog.csdn.net/PZHU_CG_CSDN/article/details/81938582