题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
解题思路
方法1:遍历链表,将节点的值存入vector中,再调用reserve进行反转
时间复杂度:O(n)
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if (head == NULL)
return res;
ListNode *node = head;
while (node != NULL)
{
res.push_back(node->val);
node = node->next;
}
reverse(res.begin(), res.end());
return res;
}
};
方法2:递归的方法,递归调用函数,递归调用后,再将node的值放入vector(链表太长,递归容易导致溢出)
时间复杂度:O(n)
class Solution {
vector<int> res;
public:
vector<int> printListFromTailToHead(ListNode *head)
{
if (head != NULL)
{
printListFromTailToHead(head->next);
res.push_back(head->val);
}
return res;
}
};
方法3:将链表反转,再遍历
时间复杂度:O(n)
class Solution {
public:
vector<int> printListFromTailToHead(ListNode *head)
{
vector<int> res;
if (head == NULL)
return res;
ListNode *currentHead = head;
ListNode *nextNode = head->next;
currentHead->next = NULL;
while (nextNode != NULL)
{
ListNode *tmp = nextNode->next;
nextNode->next = currentHead;
currentHead = nextNode;
nextNode = tmp;
}
while (currentHead != NULL)
{
res.push_back(currentHead->val);
currentHead = currentHead->next;
}
return res;
}
};