剑指offer3
作者:互联网
- 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
方法1
先顺序存入vector,再反向读取vector.back()
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> array;
ListNode *h = head;
while(h != nullptr)
{
array.push_back(h->val);
h = h->next;
}
vector<int> res;
while(array.size() != 0){
res.push_back(array.back());
array.pop_back();
}
return res;
}
};
方法2
用栈实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<ListNode*> nodes;
ListNode *h = head;
while(h != nullptr)
{
nodes.push(h);
h = h->next;
}
vector<int> res;
while(!nodes.empty())
{
h = nodes.top();
res.push_back(h->val);
nodes.pop();
}
return res;
}
};
方法3
能用栈实现自然就能用递归实现
标签:ListNode,val,res,back,next,vector,offer3 来源: https://blog.csdn.net/qq_34788903/article/details/104891861