题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解法1:逐个访问链表元素并利用insert插入到vector的头部
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v1;
while (head!= NULL)
{
v1.insert(v1.begin(),head->val);
head = head->next;
}
return v1;
}
};
Remark: while循环的判定需要是head ! =NULL,而不是head->next != NULL,这是因为需要先判定head非空才可以进一步判断head->next是否为空
解法2:递归
class Solution {
public:
vector<int> value;
vector<int> printListFromTailToHead(ListNode* head) {
if (head!= NULL)
{
value.insert(value.begin(),head->val);
printListFromTailToHead(head->next);
}
return value;
}
};
其实递归和解法1的区别就在于是while循环还是if判断…