Table of contents
One: topic
Enter the head node of a linked list, and return the value of each node from the end to the head in turn (returned in an array).
Example 1:
Input: head = [1,3,2] Output: [2,3,1]
Two: problem-solving ideas
The first way: recursive
We additionally set a vector to return
private:
vector<int> ret;
Add the input [1,3,2] in our original vector, then the order in our new vector should be [2,3,1]
Therefore, we judge whether the head pointer of the original vector is empty, and if it is not empty, we will go backwards until the last number position, and then press it forward into the new vector in turn.
Finally return the new vector
if(head)
{
reversePrint(head->next);//循环到最后一个数位置
ret.push_back(head->val);//从最后一个数往前压入新的vector中
}
return ret;//返回新的vector
code:
class Solution {
private:
vector<int> ret;
public:
vector<int> reversePrint(ListNode* head) {
if(head)
{
reversePrint(head->next);
ret.push_back(head->val);
}
return ret;
}
};
The second way: stack
Anyway, it’s all from the back to the front, then we can also use the stack to store, isn’t it the same to get the data one by one from the top of the stack?
Define a stack, and a vector to return
private:
stack<int> ret;
vector<int> num;
Push all the data onto the stack
if(head)
{
ret.push(head->val);
reversePrint(head->next);
}
Pop all the data in the stack out of the stack into the new vector, and finally return
while(!ret.empty())
{
num.push_back(ret.top());
ret.pop();
}
return num;
code:
class Solution {
private:
stack<int> ret;
vector<int> num;
public:
vector<int> reversePrint(ListNode* head) {
if(head)
{
ret.push(head->val);
reversePrint(head->next);
}
while(!ret.empty())
{
num.push_back(ret.top());
ret.pop();
}
return num;
}
};