剑指offer

Problem

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

Solution

  • 利用栈

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    class 
    {
    public:
    vector<int> printListFromTailToHead(ListNode* head)
    {
    stack<ListNode*> nodes;
    vector<int> arrayList;

    ListNode* node = head;

    while(node != NULL)
    {
    nodes.push(node);
    node = node->next;
    }

    while(!nodes.empty())
    {
    node = nodes.top();
    arrayList.push_back(node->val);
    nodes.pop();
    }

    return arrayList;
    }
    };
  • 递归

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class  {
    public:
    vector<int> arrayList;
    vector<int> printListFromTailToHead(ListNode* head)
    {
    ListNode* node = head;

    if (node != NULL)
    {
    if (node->next != NULL)
    {
    printListFromTailToHead(node->next);
    }
    arrayList.push_back(node->val);
    }

    return arrayList;
    }
    };