- Introducir una lista, devolviendo una lista secuencial desde la cola hasta la cabeza de ArrayList.
método 1
Se almacenan secuencialmente en el primer vector, y después lee inversa 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;
}
};
método 2
pila implementada
/**
* 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;
}
};
método 3
Puede apilar aplicación se puede lograr utilizando la naturaleza recursiva