输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
第一种方法,直接反转
class Solution {
public:
vector<int>m;
vector<int> reversePrint(ListNode* head) {
while(head)
{
m.push_back(head->val);
head=head->next;
}
reverse(m.begin(),m.end());
return m;
}
};
由上面的代码学习到,C++代码的链表的值,可以直接用val表示,它的值head->val,它的指向head->next;
第二种方法:
class Solution {
public:
vector<int>m;
vector<int> reversePrint(ListNode* head) {
stack<int>s;
while(head)
{
s.push(head->val);//不是push_back
head=head->next;
}
while(!s.empty())//这个循环不要忘
{
m.push_back(s.top());
s.pop();//清空栈
}
return m;
}
};
第三种方法,利用递归:
class Solution {
public:
vector<int>m;
vector<int> reversePrint(ListNode* head) {
//1.结束条件
if(head == nullptr)//这个代表空指针
return res;
//2.找等价关系=头节点后面排序,然后把头节点插进去
//插进去自然的放在最后,最后返回容器
//对头节点后面的进行排序
m=reversePrint(head->next);//这个是原函数,我还在瞎找!
m.push_back(head->val);
return m;
}
};