栈的方法:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> st;/*定义一个人空栈*/
while(head!=nullptr)//头结点不能为空
st.push(head->val),head=head->next;//从头结点开始一个个放入栈中
vector<int> ret;//定义一个容器
while(!st.empty())//判断在栈不为空的时候执行
ret.push_back(st.top()),st.pop();//执行pop元素放入容器
return ret;
}
};
递归的方法:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
dfs(head,ret);
return ret;
}
void dfs(ListNode *head,vector<int> &ret){
if(head== nullptr)
return ;
dfs(head->next,ret);
ret.push_back(head->val);
}
};
头插法复杂度为O(n^2)
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> v;
while(head != NULL)
{
v.insert(v.begin(),head->val);
head = head->next;
}
return v;
}
};
反向迭代器:
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> v;
ListNode *p = head;
while (p != nullptr) {
v.push_back(p->val);
p = p->next;
}
//反向迭代器创建临时对象
return vector<int>(v.rbegin(), v.rend());
}
};
使用库函数reverse:
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> value;
if(head != NULL)
{
value.insert(value.begin(),head->val);
while(head->next != NULL)
{
value.insert(value.begin(),head->next->val);
head = head->next;
}
}
return value;
}
};