剑指 Offer 06. 从尾到头打印链表https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
法1:(遍历一次链表)
- 先将链表元素读入数组
- 再将数组反转
vector<int> reversePrint(ListNode* head) {
// base case
if (head == nullptr)
{
return {};
}
// 先将元素读入数组
vector<int> res;
while (head != nullptr)
{
res.push_back(head->val);
head = head->next;
}
// 再对数组进行反转
reverse(res.begin(), res.end());
return res;
}
法2:(遍历两次链表)
- 先遍历一次链表,获取链表大小
- 再根据链表大小,倒序将链表元素读入数组
vector<int> reversePrint(ListNode* head) {
// base case
if (head == nullptr)
{
return {};
}
// 先获取链表长度
int size = 0;
ListNode* cur = head;
while (cur != nullptr)
{
++size;
cur = cur->next;
}
// 再遍历一次,直接倒序将元素读入数组
vector<int> res(size);
cur = head;
for (int i = size - 1; i >= 0; --i)
{
res[i] = cur->val;
cur = cur->next;
}
return res;
}