题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题意:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
方法一:利用向量按头到尾存储链表中的每个值,然后将向量反转返回
/**
* 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> ans;
while(head!=NULL)//当头节点不为空时
{
ans.emplace_back(head->val);//往数组中放入对应的val
head = head->next;//更新头节点为下一个节点
}
reverse(ans.begin(),ans.end());//颠倒ans
return ans;//返回结果
}
};
方法二:辅助栈存储,再从栈顶将元素一一返回
/**
* 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) {
stack<int> st;//辅助栈
while(head!=NULL)//枚举链表里的每个节点
{
st.push(head->val);//往栈中插入元素
head = head->next;//更新当前节点为下一个节点
}
vector<int> vct;//用于存储的向量
while(!st.empty())//将栈中的每一个元素打入向量
{
vct.emplace_back(st.top());//将栈顶元素放入向量
st.pop();//栈顶元素出栈
}
return vct;//返回向量
}
};
方法三:递归寻找
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
vector<int> vct;//定义向量
void recur(ListNode* head)//递归函数
{
if(head==NULL) return;//边界条件,节点为空
recur(head->next);//递归下一节点
vct.emplace_back(head->val);//往向量中放入对应值
}
public:
vector<int> reversePrint(ListNode* head) {
recur(head);//递归,寻找头节点
return vct;//返回向量
}
};