从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
注意:head中也有值,不是从head->next开始才有值的。
此题比那个没有让你在原链表上进行逆序,只是让你返回一个逆序的值序列而已
c++代码如下:
 
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
    ListNode *p=head;//结果向量
    vector<int> res;
    if(p==NULL) return res;    
    
    while(p){
    res.push_back(p->val);//顺序接收链表的值
    p=p->next;    
    }    
    reverse(res.begin(),res.end());//逆序   
    return res;   
    }
};
不一样的烟火
原文地址:https://www.cnblogs.com/cstdio1/p/11236516.html