topic
Enter a head of the list nodes, each node in turn, the return value (Return an array) from the tail to the head.
Example 1:
输入:head = [1,3,2]
输出:[2,3,1]
limit:0 <= 链表长度 <= 10000
A thought: Reverse Array
Code
Time complexity: O (n)
complexity of space: O (1)
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
if (!head) return res;
while (head != nullptr) {
res.push_back(head->val);
head = head->next;
}
reverse(res.begin(), res.end());
return res;
}
};
Thinking two: Stack
Code
Time complexity: O (n)
space complexity: O (n)
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
if (!head) return res;
stack<int> st;
while (head != nullptr) {
st.push(head->val);
head = head->next;
}
while (!st.empty()) {
res.push_back(st.top());
st.pop();
}
return res;
}
};