[剑指offer] 3. 从头到尾打印链表

题目描述

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

思路:
利用容器,遍历一遍加入到一个新容器里,然后反置输出。
vector 用 reverse
stack 则直接一个个出栈。
class Solution
{
public:
  vector<int> printListFromTailToHead(ListNode *head)
  {
    vector<int> res;
    while (head != NULL)
    {
      res.push_back(head->val);
      head = head->next;
    }
    reverse(res.begin(), res.end());
    return res;
  }
};
原文地址:https://www.cnblogs.com/ruoh3kou/p/10042428.html