输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
反向迭代器思路:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> v;
ListNode *p = head;
while (p != NULL) {
v.push_back(p->val);
p = p->next;
}
//反向迭代器创建临时对象
return vector<int>(v.rbegin(), v.rend());
}
};
栈思路:
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> value;
ListNode *p=NULL;
p=head;
stack<int> stk;
while(p!=NULL){
stk.push(p->val);
p=p->next;
}
while(!stk.empty()){
value.push_back(stk.top());
stk.pop();
}
return value;
}
};