Problem Description
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
Mentality
逆序类操作,可使用栈进行中转。
遍历一遍链表,将数值存储在栈中,再从栈中取出数放于数组即可。
Code (C++)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
const int maxSize=100000;
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* p;
int stack[maxSize] = { 0 };
int top = -1;
p = head;
while (p != NULL) {
stack[++top] = p->val;
p = p->next;
}
vector<int> tail(top + 1);
int i(0);
while (top != -1) {
tail[i++] = stack[top--];
}
return tail;
}
};
已通过所有的测试用例,欢迎指正批评(´▽`ʃ♡ƪ)