输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路:设置一个stack,入栈出栈
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//返回
vector<int> out;
//链表栈
int top = -1;
int stack[20];
//入栈
ListNode *p = head;
while(p != NULL)
{
stack[++top] = p->val;
p = p->next;
}
//出栈
while(top != -1)
{
out.push_back(stack[top--]);
}
return out;
}
};