题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000

方法一:遍历链表从尾到头依次输出
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> array;
ListNode* cur = head;
ListNode* tail = NULL;
while(head != tail)
{
cur = head;
while(cur->next != tail)
{
cur = cur->next;
}
array.push_back(cur->val);
tail = cur;
}
return array;
}
};
方法二:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> node;
vector<int> val;
ListNode* pNode = head;
while(pNode != NULL)
{
node.push(pNode->val);
pNode = pNode->next;
}
while(!node.empty())
{
val.push_back(node.top());
node.pop();
}
return val;
}
};
方法三:用反向迭代器实现
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> array;
ListNode* cur = head;
while(cur)
{
array.push_back(cur->val);
cur = cur->next;
}
//反向迭代器
return vector<int>(array.rbegin(),array.rend());
}
};

322

被折叠的 条评论
为什么被折叠?



