问题描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
注意事项
全在注释里了
实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vec;
ListNode *pre=nullptr, *aft;
while(head){//反转链表
aft = head->next;
head->next = pre;
pre = head;
head = aft;
}
head = pre;//倒序遍历
if(!head) return vec;//使用head->next一定要保证head不是空指针
while(head)
{
vec.push_back(head->val);
head = head->next;
}
return vec;
}
};