- Enter a list, by returning a list sequentially from the tail to the head of ArrayList.
method 1
Are sequentially stored in the first vector, and then reverse read 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;
}
};
Method 2
Stack implemented
/**
* 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;
}
};
Method 3
Can stack implementation can be achieved using recursive nature