方法1,暴力法,先从头到尾遍历链表,将链表元素保存到数组中,然后再反向遍历数组:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public:vector<int> reversePrint(ListNode* head) {vector<int> a1,a2;for (ListNode *i = head;i!=nullptr;i=i->next) {a1.push_back(i->val);}for (int i=a1.size()-1;i>=0;i--) {a2.push_back(a1[i]);}return a2;}};
这种方法效率不高,在leedcode通过:
执行用时:4 ms, 在所有 C++ 提交中击败了75.94% 的用户内存消耗:8.6 MB, 在所有 C++ 提交中击败了38.98% 的用户
方法2,遍历链表,将数据放入栈中,然后返回
