题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//用栈的思路来实现
std::stack<int> nodes;
vector<int> outnodes;
ListNode *pNode = head;
//把链表每经过一个节点时,都把它放到栈中
while(head != NULL)
{
nodes.push(head->val);
head = head->next;
}
//从栈顶逐个输出节点的值,此时输出节点的顺序已经反转过来了
while(!nodes.empty())
{
outnodes.push_back(nodes.top());
nodes.pop();
}
return outnodes;
}
};