题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路
利用栈“先进后出”的性质,将链表的值存入到栈里,然后将栈里的值存入到构建好的容器里,最后打印容器。
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> result;
        stack<int> arr;
        ListNode* p = head;
        while(p!=NULL)
        {
            arr.push(p->val);
            p = p->next;
        }
        int len = arr.size();
        for(int i =0;i < len;i++)
        {
            result.push_back(arr.top());
            arr.pop();
        }
        return result;
    }
        
};

 

相关文章:

  • 2021-06-12
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-01-29
  • 2021-07-05
  • 2022-12-23
相关资源
相似解决方案