题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
思路一:
从尾到头,刚好是先进后出,栈结构,把链表从头到尾依次入栈,然后从栈顶到栈底,依次出栈,即是答案。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (head == nullptr) {
return {};
}
stack<int> stk;
ListNode* tmp = head;
while(tmp != nullptr) {
stk.push(tmp->val);
tmp = tmp->next;
}
vector<int> ans;
while(!stk.empty()) {
ans.emplace_back(stk.top());
stk.pop();
}
return ans;
}
};
思路二 递归。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
vector<int> ans;
public:
vector<int> reversePrint(ListNode* head) {
if(head != nullptr) {
if(head->next != nullptr) {
reversePrint(head->next);
}
ans.emplace_back(head->val);
}
return ans;
}
};